Leetcode_Two Sum II
来源:互联网 发布:手机伴唱软件 编辑:程序博客网 时间:2024/05/29 17:04
Tag
Array\Two Pointers\Binary Search
Difficulty
Easy
Description
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Code
正常思路,一个一个搜索,时间复杂度O(n^2)
因为是有序数组,所以可以用二分搜索,复杂度降为O(nlogn)
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): tmp=target-nums[i] start=i+1 end=len(nums)-1 while(start<=end): if tmp==nums[end]: return [i+1,end+1] if tmp==nums[start]: return [i+1,start+1] mid = (end - start) / 2+start if mid==start or mid==end: break if tmp > nums[mid]: start=mid elif tmp< nums[mid]: end=mid else: return [i+1,mid+1]
0 0
- Leetcode_Two Sum II
- leetcode_Two Sum II
- leetcode_Two Sum
- Leetcode_Two Sum
- LeetCode_Two Sum
- LeetCode_Two Sum
- LeetCode_Two Sum
- LeetCode_Two Sum
- leetcode_two sum
- Leetcode_Two Sum
- leetcode_Two sum
- leetcode_Two Sum
- leetcode_two sum()
- Leetcode_two-sum (c++ and python version)
- 【Leetcode】Path Sum II (Sum)
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- Combination Sum II
- error while loading shared libraries: libgcc_s.so.1: cannot open shared object file: Input/output er
- 结识git(一)
- sql优化
- 第十一讲项目二 分离小数和整数
- CentOS下启动不了eclipse
- Leetcode_Two Sum II
- The Linux Programming Interface 00 preface 序言
- Google VR技术大揭秘
- jsp中输入框字符校验
- 盘点我经常用到的linux命令
- Android API 指南
- leetCode 56, Merge Intervals
- 关于SSH框架文件上传到服务器自动删除问题的解决方法。
- Nginx的优化