题目:
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.
1 2 3 4 5 6
| Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
|
思路:
在找的过程中建立索引,故一个循环可以求出解(总是使用未使用元素查找使用元素,可以保证每一对都能被检索到)
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++){ int num=target-nums[i]; if(m.containsKey(num)) return new int[]{m.get(num),i}; m.put(nums[i],i); } throw null; } }
|
Status | Runtime | Language |
---|
Accepted | 8ms | java |