LeetCode #167 Two Sum II
来源:互联网 发布:java并发框架有哪些 编辑:程序博客网 时间:2024/05/21 10:32
原题:
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
技巧学习:
双指针:在排好序的数组中使用
-binary search
暴力解法:
这题同样可以用#1的方法解,但没有用到顺序这个条件。
注意:
1)if(numbers[numbers.length-1] == numbers[0])
throw new IllegalArgumentException("No Two Sum Solution");
TestCase里给出无数个0但target不等于0的情况,所以排除了这个。但是比较机械。
2)testcase里有负数!!
Time Complexity: O(n)
Space Complexity: O(n)
双指针解法:
注意:
1)因为头尾指针make progress to the middle,所以不用担心000...0的case。
2)有人指出,两个int相加有可能超出int范围,故用long。
Time Complexity: O(n)
Space Complexity: O(1)
- Leetcode #167 Two Sum II
- Leetcode 167 Two Sum II
- LeetCode 167 Two Sum II
- LeetCode[167]Two Sum II
- LeetCode-167:Two Sum II
- leetcode 167--- Two Sum II
- LeetCode #167 Two Sum II
- [leetcode] Two Sum II
- LeetCode : Two Sum II
- leetcode [Two Sum II
- 【LeetCode】Two Sum II
- 【leetcode】Two Sum II
- LeetCode:Two Sum II
- leetcode--Two Sum II
- leetcode Two Sum II
- leetcode -- Two Sum II
- leetCode-Two Sum II
- [Leetcode]1(167). Two Sum I, II
- 文章转载
- java io学习---tomcat
- vueJS组件笔记(针对.vue组件)
- c#接收ios上传图片保存后文件损坏
- 一分钟建立Spark集群环境
- LeetCode #167 Two Sum II
- ivew的Table中使用render添加图片poptip冒泡方法
- VUE-element-from
- mtk平台android隐藏第三方不可访问的rom空间
- 给任务排序(uva 10305)
- 判断是否是2的指数次幂
- Spring Cloud原理分析及使用<二>
- Docker安装Confluence6.6破解
- 使用Beautifulsoup解析本地html文件