LeetCode 1. Two Sum

原题链接在这里:https://leetcode.com/problems/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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题解:

采用HashMap记录之前出现的num 和 其对应的 index.

Time Complexity: O(n). Space: O(n).

AC Java:

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         if(nums == null || nums.length < 2){
 4             throw new IllegalArgumentException("Invalid input.");
 5         }
 6         
 7         int [] res = {-1, -1};
 8         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
 9         for(int i = 0; i<nums.length; i++){
10             if(!hm.containsKey(target - nums[i])){
11                 hm.put(nums[i], i);
12             }else{
13                 res[0] = hm.get(target-nums[i]);
14                 res[1] = i;
15                 break;
16             }
17         }
18         
19         return res;
20     }
21 }

AC C++:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         unordered_map<int, int> map;
 5         for(int i = 0; i < nums.size(); i++){
 6             if(map.find(target - nums[i]) != map.end()){
 7                 return {map[target - nums[i]], i};
 8             }else{
 9                 map[nums[i]] = i;
10             }
11         }
12 
13         return {-1, -1};
14     }
15 };

跟上Two Sum II - Input array is sortedTwo Sum III - Data structure designTwo Sum IV - Input is a BST3Sum3Sum Closest4Sum.

posted @ 2015-12-12 04:50  Dylan_Java_NYC  阅读(353)  评论(0编辑  收藏  举报