Two Sum和Three Sum
1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
public int[] twoSum(int[] nums, int target) {
HashMap< Integer, Integer> map=new HashMap<Integer,Integer>();
int []res=new int[2];
int n=nums.length;
for(int i=0;i<n;i++){
map.put(nums[i],i);
}
for(int i=0;i<n;i++){
int t=target-nums[i];
if(map.containsKey(t)&&map.get(t)!=i){
res[0]=i;
res[1]=map.get(t);
break;
}
}
return res;
}
2.Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
List<List<Integer>> res=new ArrayList<List<Integer>>();
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums); //排序的时间复杂度为O(n*lgn);
int len=nums.length;
for(int i=0;i<len-2;i++){
if(i>0&&nums[i]==nums[i-1])
continue; //跳过相同的结果
int l=i+1;
int r=len-1;
int target=nums[i];
while(l<r){
if(nums[l]+nums[r]+target==0){
res.add(Arrays.asList(nums[l],nums[r],target));
while(l<r&&nums[l]==nums[l+1]) l++; //跳过重复的结果
while(l<r&&nums[r]==nums[r-1]) r--; //跳过重复的结果
l++;
r--;
}
else if(nums[l]+nums[r]+target<0){
l++;
}
else{
r--;
}
} //找到与num[i]相加等于0地两个数。
}
return res;
}