##引言:
Two Sum类问题属于对撞型双指针问题,这类问题的思路不难,但是变形以及问法比较多,这里将部分题目做归纳总结。
在Two Sum问题中,需要用的预处理为排序。但有的时候需要返回索引的位置,就需要设计数据结构先保存索引信息,再进行排序。如果不想这样麻烦的话,可以借助哈希表这个常用的数据结构来代替双指针。
##题解:
1.两数之和 II Two Sum问题的基本变形,在一组整数中找出多少对整数,大于给定目标值。
基本思路:排序预处理 + 双指针
Code:
public class Solution {
/**
* @param nums: an array of integer
* @param target: an integer
* @return: an integer
*/
public int twoSum2(int[] nums, int target) {
// Write your code here
if (nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int count = 0;
int i = 0;
int j = nums.length - 1;
while (i < j) {
if (nums[i] + nums[j] > target) {
count += j - i;
j--;
} else {
i++;
}
}
return count;
}
}
2.3Sum Closest
基本思路:2Sum Closet的变形。
这里有抽出函数的写法和不抽出函数的写法,
另外nums[A] + nums[B] + nums[C] = target + closet.
特别注意这里函数的写法和初始化,推荐用函数写法。
Code:
public class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3)