LeetCode0167.两数之和 II - 输入有序数组
2021-04-13 12:26
标签:tps target pre null ble inf else 答案 ima
可以用双指针法, 分别指向头尾元素,如果两元素的和大于目标,尾指针前移,如果小于目标,头指针后移,等于目标即可得答案
LeetCode0167.两数之和 II - 输入有序数组 标签:tps target pre null ble inf else 答案 ima 原文地址:https://www.cnblogs.com/KingR/p/13343130.html题目要求
算法分析
代码展示(C#)
public class Solution {
public int[] TwoSum(int[] numbers, int target) {
if(numbers.Length == 0){return null;}
int[] ret = new int[2];
int p1 = 0,p2 = numbers.Length - 1;
while(p1 p2){
int temp = numbers[p1] + numbers[p2];
if(temp == target){
ret = new int[2]{p1+1,p2+1};
break;
}
else if(temp target){
p1++;
}
else if(temp > target){
p2--;
}
}
return ret;
}
}
提交结果
文章标题:LeetCode0167.两数之和 II - 输入有序数组
文章链接:http://soscw.com/index.php/essay/75181.html