1. Two Sum
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
这个数组是无序的
java(8ms):
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 int[] res = new int[2] ; 4 HashMap<Integer,Integer> map = new HashMap() ; 5 for(int i = 0 ; i < nums.length ; i++){ 6 if (map.containsKey(target - nums[i])){ 7 res[1] = i ; 8 res[0] = map.get(target - nums[i]) ; 9 return res ; 10 } 11 map.put(nums[i], i) ; 12 } 13 return res ; 14 } 15 }
C++(9ms):
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> res ; 5 int len = nums.size() ; 6 unordered_map<int,int> map ; 7 for(int i = 0 ; i < len ; i++){ 8 if (map.find(target - nums[i]) != map.end()){ 9 res.push_back(map[target - nums[i]]) ; 10 res.push_back(i) ; 11 return res ; 12 } 13 map[nums[i]] = i ; 14 } 15 16 return res ; 17 } 18 };