Find the point in array with equal sum of left and right. 找数组中的一个点, 使左右的合相等
给一个数组, 找数组中的一个点, 使在这点的左边数的和,等于右边的和.
注意: 这里不是sorted数组. 所以我们用meet in middle的做法. 而且数组会有负数, 对于负数, 我们需要在另一边加上这个数.
public int find (int[] nums) { int l = 0; int r = nums.length - 1; int suml = 0; // sum of left side int sumr = 0; // sun of right side while (l <= r) { if (l == r && suml == sumr) // if it is the result return l; else if (suml > sumr){ // if left side is larger if (nums[r] > 0) { // if the next element of right is positive sumr += nums[r]; // pick right next element r--; } else if (nums[l] < 0){ // if the next element of left is negative suml += nums[l]; // pick left next element l++; } else { // have no greedy choice in this step, just move on sumr += nums[r]; suml += nums[l]; r--; l++; } } else{ if (nums[l]>0) { suml += nums[l]; l++; }else if (nums[r] < 0){ sumr += nums[r]; r--; } else { sumr += nums[r]; suml += nums[l]; r--; l++; } } } return -1; }
Leave A Comment