原题
1. Two Sum
Difficulty: Easy
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
tips:
1. 本题数组是没有排序的;
2. 使用hashmap来求解,需要保证数组是没有重复元素的;
3. 时间复杂度O(N),空间复杂度也是O(N);
代码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums==null&&nums.length<=0)
return null;
HashMap<Integer,Integer> hashMap=new HashMap<>();
int []res=new int[2];
for(int j=0;j<nums.length;j++){
int temp=target-nums[j];
if(hashMap.containsKey(temp)&&hashMap.get(temp)!=j){
res[0]=j;
res[1]=hashMap.get(temp);
break;
}
else
hashMap.put(nums[j],j);
}
return res;
}
}