Two Sum II - Input array is sorted
来源:互联网 发布:zygote启动优化 编辑:程序博客网 时间:2024/05/21 11:09
https://oj.leetcode.com/problems/two-sum-ii-input-array-is-sorted/
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
这一题在最初的two sum就讲过了。如果是一个排好序的数组,就头尾向中间聚集就好了。如果和比target大,就尾指针往前移,如果比target小就头指针往后移。这种题目已经出的太烂了,现在的面试过程中遇到的可能性已经很小了。就给出代码如下:
public int[] twoSum(int[] numbers, int target) { int head = 0, tail = numbers.length - 1; int[] res = new int[2]; while(head < tail){ if(numbers[head] + numbers[tail] < target) head++; else if(numbers[head] + numbers[tail] > target) tail--; else{ res[0] = head + 1; res[1] = tail + 1; return res; } } return res; }
0 0
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Leetcode167 - Two Sum II - Input array is sorted(two pointers)
- leetcode 167: Two Sum II - Input array is sorted
- Leetcode NO.167 Two Sum II - Input array is sorted
- LeetCode-Two Sum II - Input array is sorted
- [Leetcode]Two Sum II - Input array is sorted
- 167 Two Sum II - Input array is sorted
- leetcode--Two Sum II - Input array is sorted
- LeetCode 题解(274) : Two Sum II - Input array is sorted
- [LeetCode] Two Sum II – Input array is sorted
- [LeetCode167]Two Sum II - Input array is sorted
- cocoapods(初步)
- spring-aop-@Aspect详细用法
- Typeclassopedia 阅读笔记:导言与 Functor
- github分享
- ANDROID模拟火花粒子的滑动喷射会不停的喷射火花粒子
- Two Sum II - Input array is sorted
- android的键盘问题
- shell脚本关于case的用法
- SwwetAlert消息提示插件,支持手机移动响应式替换alert漂亮的消息提示插件
- iosUIToolBar工具条的使用
- 指针数组和数组指针
- cocoapods(进阶)
- oracle循环
- Java面向对象的知识(一)