双指针 05

149 阅读1分钟

LeetCode 167

leetcode-cn.com/problems/tw…

代码如下:

/**
 * 双指针
 * 
 * 两个指针在两端,如果和比target大,右指针向左缩小范围
 * 小,则左指针向左放大,直到找到目标
 */
class Solution {
	public int[] twoSum(int[] numbers, int target) {
		int left = 0, right = numbers.length - 1;
		while(left < right) {
			int sum = numbers[left] + numbers[right];
			if (sum < target) {
				left ++;
			} else if (sum > target) {
				right --;
			} else {
				return new int[] {left+1, right+1};
			}
		}
		return new int[] {-1, -1};
	}

//	public static void main(String[] args) {
//		Solution k = new Solution();
//		int[] a = new int[] { 2, 7, 11, 15 };
//		System.out.println(Arrays.toString(k.twoSum(a, 9)));
//	}
}