【LeetCode】Two Sum

Two Sum 
Total Accepted: 7616 Total Submissions: 34943 My Submissions
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
【解题思路】
早上出门前A了一道题。
发现在提交的过程中,如果有测试用例没过,会把用例打印出来,给了很多思路。
这个题是求数组中的两个数和为target的index1和index2。
我使用了Map,循环一遍数组,将值作为key,index作为value,因为key可能有重复,所以value为list。
存储的时候,list按照的就是key出现的顺序。比如5出现了两次,那么list存储的两个数肯定是从小到大的。
这样就把key和index存储了。
然后对数组进行排序。
依次循环数组,判断target-numbers[i]在不在map中,如果在的话,那么index就求出来了。
这里有个陷阱,如果target-numbers[i] == numbers[i],那么index就应该是map.get(numbers[i])中的第一个和第二个。

Java AC

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int len = numbers.length;
        Map<Integer,List<Integer>> numMap = new HashMap<Integer,List<Integer>>();
        List<Integer> indexList = new ArrayList<Integer>();
        for(int i = 0; i < len; i++){
            indexList = numMap.get(numbers[i]);
            if(indexList == null){
                indexList = new ArrayList<Integer>();
            }
            indexList.add(i);
            numMap.put(numbers[i],indexList);
        }
        Arrays.sort(numbers);
        int []array = new int[2];
        for(int i = 0; i < len; i++){
            int result = target - numbers[i];
            if(numMap.containsKey(result)){
                if (result == numbers[i]) {
            		List<Integer> keyList = numMap.get(numbers[i]);
            		array[0] = keyList.get(0)+1;
            		array[1] = keyList.get(1)+1;
				}else {
					array[0] = numMap.get(numbers[i]).get(0)+1;
	            	array[1] = numMap.get(result).get(0)+1 ;
				}
            	break;
            }
        }
        Arrays.sort(array);
        return array;
    }
}

你可能感兴趣的:(【LeetCode】Two Sum)