Two Sum

2019-05-03  本文已影响0人  ae12

use hashmap strore the data
the time complexity is about o(n) cost in the traversal of the int array;and the map cost o(1) if not collistion,however if the collision exist ,time cost is o(n)
the space complexity is o(n) store the value

public int [] twoSum(int [] sums,int target){
Map<Integer,Integer> map =new HashMap();
for(int i=0;i<sum.length;i++){
int complement =tatget - sums[i];
if(map.containKey(complement)){
return new Int[]{i,map.get(complement)}
}
map.put(sum[i],i]);
}

上一篇下一篇

猜你喜欢

热点阅读