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.

Example:

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

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

链接:https://leetcode.com/problems/two-sum/

一刷

python

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        existing_data = {}
        for index, num in enumerate(nums):
            lookup_value = target - num
            if lookup_value in existing_data:
                return existing_data[lookup_value], index
            existing_data[num] = index

swift

    func twoSum(nums: [Int], _ target: Int) -> [Int] {
        var valueIndex = [Int: Int]()
        for (index, value) in nums.enumerate() {
            var pairValue: Int = target - value
            if let pairIndex = valueIndex[pairValue] {
                return [pairIndex, index]
            }
            valueIndex[value] = index
        }
        return [-1, -1]
    }

 

2/5/2017 今天开始重新刷题,并且用Java刷题。

这道题完全不会做了,应该是没有经过任何思考,直接按照头脑里的想法来写的。我想如果是Python的话因为我对语言的了解程度可能一开始就会想出最优解并不会出错,但是对Java不了解,不但解决语法问题耽误时间,而且也造成了算法错误。

一开始的错误解法是先把每个元素的index放到hashmap当中,然后sort数组,再来查找。我不知道为什么已经选择了hashmap我还要sort,可能好久没看算法敏感度下降了。出现的错误例子就是input [3, 3], target=6的时候,第二个index把第一个给覆盖了。

下面是正确做法:

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         HashMap<Integer, Integer> dict = new HashMap<Integer, Integer>();
 4         int ret[] = new int[]{-1, -1};
 5         
 6         for (int i = 0; i < nums.length; i++) {
 7             if (dict.containsKey(target - nums[i])) {
 8                 ret[0] = i;
 9                 ret[1] = dict.get(target - nums[i]);
10                 return ret;
11             } else {
12                 dict.put(nums[i], i);
13             }
14         }
15         return ret;
16     }
17 }

学到的语法知识:

最后必须return, 此例当中还需要保证ret已经初始化;

HashMap的各种函数并不如Python dict用起来顺手,语言老旧。

posted @ 2016-05-30 22:37  panini  阅读(176)  评论(0编辑  收藏  举报