1 two sum

| 分类 leetcode  | 标签 array 

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

tags:array hash table

1

很容易想到暴力解法,brute force。提交之后居然没有超时,504ms,顺便吐槽一句leetcode每次的运行时间有时候相差很大。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        if(nums == null) return null;
        for (int i = 0; i < nums.length; i++ ) {
                int another = target - nums[i];
                for(int j = i+1; j < nums.length; j++){
                    if(nums[j] == another)
                    {
                        result[0] = i+1;
                        result[1] = j+1;
                        return result;
                    }
                }      
} return null;

<span class="o">}</span><span class="w">

tags中提示hash table,使用hashtable会比较快些。

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

<span class="o">}</span><span class="w">

在这道题的solution提示:

O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

因为使用的hashtable,get() containsKey()的时间复杂度为O(1) 我觉得既然是练习算法,最好还是自己尽量少的使用语言的语法糖,看来以后还是应该使用c语言实现一遍。

2 most votes

基本上也是使用hashtable map等。


上一篇     下一篇