public List<List<Integer>> threeSum(int[] numbers) { Arrays.sort(numbers); List<List<Integer>> results = new ArrayList<>(); for (int i = 0; i < numbers.length; i++) { if (i != 0 && numbers[i] == numbers[i - 1]) { continue; } findTwoSum(numbers, i, results); } } privatevoidfindTwoSum(int[] nums, int index, List<List<Integer>> results){ int left = index + 1, right = nums.length - 1; int target = -nums[index]; while (left < right) { int twoSum = nums[left] + nums[right]; if (twoSum < target) { left++; } elseif (twoSum > target) { right--; } else { List<Integer> triple = new ArrayList(); triple.add(nums[index]); triple.add(nums[left]); triple.add(nums[right]); results.add(triple); left++; right--; //113422 while (left < right && nums[left] == nums[left - 1]) { left++; } } } }
triangle count
a <= b <= c, a + b > c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicinttriangleCount(int S[]){ int left = 0, right = S.length - 1; int ans = 0; Arrays.sort(S); for (int i = 0; i < S.length; i++) { left = 0; right = i - 1; while (left < right) { if (S[left] + S[right] > S[i]) { //left +1, left + 2 ,,, 都可以 a+b>c ans = ans + (right - left); right--; } else { left++; } } } return ans; }
publicclassSolution{ public List<List<Integer>> fourSum(int[] num, int target) { List<List<Integer>> rst = new ArrayList<List<Integer>>(); Arrays.sort(num);
for (int i = 0; i < num.length - 3; i++) { if (i != 0 && num[i] == num[i - 1]) { continue; }
for (int j = i + 1; j < num.length - 2; j++) { if (j != i + 1 && num[j] == num[j - 1]) continue;
int left = j + 1; int right = num.length - 1; while (left < right) { int sum = num[i] + num[j] + num[left] + num[right]; if (sum < target) { left++; } elseif (sum > target) { right--; } else { ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.add(num[i]); tmp.add(num[j]); tmp.add(num[left]); tmp.add(num[right]); rst.add(tmp); left++; right--; while (left < right && num[left] == num[left - 1]) { left++; } while (left < right && num[right] == num[right + 1]) { right--; } } } } }
publicclassSolution{ publicvoidsortColors(int[] nums){ int left = 0; int right = nums.length - 1; int mid = 0; //直到mid > right停止遍历 while (mid <= right){ if (nums[mid] == 0){ swap(nums, mid, left); mid ++; left ++; } elseif (nums[mid] == 2){ swap(nums, mid, right); right --; } else{ mid ++; } } } privatevoidswap(int[] a, int i, int j){ int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } }
publicclassSolution{ /** * @param s: A string * @return: Whether the string is a valid palindrome */ publicbooleanisPalindrome(String s){ // write your code here if(s == null || s.length() == 0){ returntrue; } int left = 0; int right = s.length() - 1;