leetcode--two_sum问题
2016-09-12 23:01
363 查看
leetcode–two_sum问题
2016-09-12问题描述: 给定一个排好序的整数数组,使得两数相加等于一个特定的值。
要求: 返回两个数在数组中的索引,第一个数的索引必须小于第二个;数组的起始下标不是从0开始的。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路
假设数组为numbers[],设置收尾指针head和tail,当numbers[head] + numbers[tail] < target时,head加1;
当numbers[head] + numbers[tail] > target时,tail减1;
当numbers[head] + numbers[tail] = target 或者 head > tail时,算法终止。
算法最终的时间复杂度为O(n)。
python程序
class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ head = 0 tail = len(numbers) - 1 while head <= tail: if numbers[head] + numbers[tail] > target: tail -= 1 elif numbers[head] + numbers[tail] < target: head += 1 else: return [head + 1, tail + 1] return None if __name__ == '__main__': temp = input('please enter a list:') nums = [int(i) for i in temp.split(' ')] target = int(input('please enter an int: ')) Solution().twoSum(nums, target)
源程序下载
原题变形
如果给定的整数数组没有排好序,如何解决两数相加等于一个特定值问题。解题思路1
先将表排序排序,再按照上述方法做,时间复杂度为O(n*logn)。解题思路2
使用HashMap,因为每次HashMap(python中为dict)找key都只要O(1)的时间复杂度,可以将原数组numbers中的值作为key,索引作为value,遍历一遍放到HashMap中。再通过遍历numbers数组中的值x,查找target-x是否为HashMap的key,此过程时间复杂度为O(n)。综上,使用HashMap的时间复杂度为O(n),空间复杂度也为O(n)。Tips: 当numbers中存在重复值时,该方法不适用。
相关文章推荐
- leetcode中第一题twosum问题解答算法的可行性证明
- LeetCode two sum问题
- leetcode系列:twosum问题
- Leetcode问题-1(Two Sum)
- leetcode之twosum问题
- leetcode之TwoSum问题
- LeetCode题解 || Two Sum问题
- 【Leetcode】之Two Sum问题
- leetcode之Two Sum问题
- LeetCode Two Sum II - Input array is sorted(Two pointer问题)
- leetcode刷题,我的解法1 twosum问题
- Leetcode之Two Sum II - Input array is sorted 问题
- Leetcode-Two Sum——K Sum问题
- Leetcode-Two Sum(2 Sum) 问题
- 【leetcode】小白题解:two sum问题
- leetcode_Two Sum II - Input array is sorted
- 【Leetcode】Sum of Two Integers
- Leetcode: Two Sum II
- LeetCode 1、Two Sum
- leetcode-1-two-sum-散列查找