LeetCode Crack Note --- 1. Two Sum

Discription

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].

Difficulty:

Solving Strategy

  1. 将原数组深拷贝一份,并进行排序,得到数组nums2;
  2. 使用两个指针,分别指向nums2的首尾,两个指针同时向中间移动,并判断当前下标对应元素的和是否等于target。(这点在特定情况下,可以节省大量时间,eg. nums=[0,1,2,3,…,9999],target=1000)

My Solution

 1 # Use Python3
 2 class Solution:
 3     def twoSum(self, nums, target):
 4         """
 5         :type nums: List[int]
 6         :type target: int:rtype: List[int]
 7         """
 8 
 9         nums2 = nums[:] # Copy a new list for sorting
10         nums2.sort()
11         ii = 0
12         count = nums.__len__()
13         jj = count-1
14 
15         val1 = 0
16         val2 = 0
17         while ii < jj:
18             if nums2[ii] + nums2[jj] == target:
19                 val1 = nums2[ii]
20                 val2 = nums2[jj]
21                 break
22             elif nums2[ii] + nums2[jj] < target:
23                 ii = ii + 1
24             elif nums2[ii] + nums2[jj] > target:
25                 jj = jj - 1
26 
27         indexList = []
28         for i in range(count):
29             if nums[i] == val1:
30                 indexList.append(i)
31                 break
32 
33         for j in range(count-1, -1, -1):
34             if nums[j] == val2:
35                 indexList.append(j)
36                 break 
37 
38         indexList.sort()
39         return [indexList[0], indexList[1]]

Runtime: 85 ms

Official Solution

Approach #1 (Brute Force) [Accepted]

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target - x.

 1 public int[] twoSum(int[] nums, int target) {
 2     for (int i = 0; i < nums.length; i++) {
 3         for (int j = i + 1; j < nums.length; j++) {
 4             if (nums[j] == target - nums[i]) {
 5                 return new int[] { i, j };
 6             }
 7         }
 8     }
 9     throw new IllegalArgumentException("No two sum solution");
10 }

Complexity Analysis:

  • Time complexity : O(n). We traverse the list containing n elements exactly twice. Since the hash table reduces the look up time to O(1), the time complexity is O(n).
  • Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly n elements.

Approach #2 (Two-pass Hash Table) [Accepted]

Approach #3 (One-pass Hash Table) [Accepted]

Reference

[南郭子綦's blog]

原文地址:https://www.cnblogs.com/gxcdream/p/7456998.html