Two Pointer
Last updated
Last updated
Two pointer 有两种解法:
1)l = 0, r = n - 1,两指针相向而行
2)l = 0, r = 1,两指针同向而行
// 两指针相向而行
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int ans = 0;
for(int l = 2; l < nums.length; l++) {
int i = 0, j = l - 1;
while (i < j) {
if (nums[i] + nums[j] > nums[l]) {
ans += j - i;
j--;
} else {
i++;
}
}
}
return ans;
}
// Store the indexes of such tri-pairs.
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null) return res;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right] + nums[i];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
res.add(Arrays.asList(i, left, right));
left++;
right--;
}
}
}
}
return res;
}
// Store the values of such tri-pairs.
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null) return res;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right] + nums[i];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
while(left < right && nums[left] == nums[left - 1]) left++;
right--;
while(left < right && nums[right] == nums[right + 1]) right--;
}
}
}
}
return res;
}
(with Dedup)