标签:tps target pre null ble inf else 答案 ima
可以用双指针法,
分别指向头尾元素,如果两元素的和大于目标,尾指针前移,如果小于目标,头指针后移,等于目标即可得答案
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; } }
标签:tps target pre null ble inf else 答案 ima
原文地址:https://www.cnblogs.com/KingR/p/13343130.html