LeetCode Crack Note --- 1. Two Sum
2016-03-01 11:37
344 查看
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
将原数组深拷贝一份,并进行排序,得到数组nums2;使用两个指针,分别指向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]相关文章推荐
- Android DiskLruCache完全解析,硬盘缓存的最佳方案
- spring AOP 实现事务和主从读写分离
- yum
- 自定义假搜索框(TF)
- ExtJS Ext.get()和Ext.getCmp()的区别
- 这是一篇独白(为没有时间学习技术的你而写)
- 隐藏软键盘方法
- leetcode 每日一题 258. Add Digits
- PHP中字符串替换函数之strtr详解
- iOS 高效添加圆角效果实战讲解
- C++ Super-FAQ 『Assignment Operators』
- 数据字典 dba_free_space及相对文件号RELATIVE_FNO 小结
- oracle中避免sort操作
- Hbase分布式安装部署过程
- 最小二乘法的几何意义 – 巧妙记忆公式的方法
- ShareSDK3.x (简洁版)遇到的坑......
- 第一行代码-10.4 解析JSON格式数据
- Android正确进行数据存储
- JSON解析
- SequoialDB实验