Sum problem

1.Two sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

Solution: First think binary search. Might not be a good solution since it needs first to be sort O(NlogN), Then search O(nlogn).

HashMap may be a good way.

1
2
3
4
5
6
7
8
9
10
11
12
13
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(map.get(target-nums[i])!=null){
result[0]=map.get(target-nums[i]);
result[1]=i;
return result;
}
map.put(nums[i],i);
}
return result;
}

2.Three Sum

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.

Solution: Brute force would be O(N^3).

In whatever way we must traverse firstly to ensure one number, then the problem would be two sum.

Hashset:O(N*N)

Sort+Two pointers: O(NlogN+N^n)