leecode 167. Two Sum II - Input array is sorted

原创 2016年08月29日 14:54:09

题意:在数组的中两个数字的和为目标数组,看了其实很简单是吧,注意有坑:人家求的事第几个,从第一个开始的。举个例子:Input: numbers={2, 7, 11, 15}, target=9 。Output: index1=1, index2=2 结果是:1,2。结果是第一个第二个。

思路:思路很简单的,两个指针一个指向头一个指向结尾,往中间遍历,人家要求第一个数字的索引要小于第二个数字的索引,

所以循环条件:头指针(begin)<为指针(end)。

情况分三种:begin+end > target ,begin+end < target ,begin+end = target。

public int[] twoSum(int[] numbers, int target) {
		int begin = 0;
		int end = numbers.length - 1;
		while (begin < end) {
			// 1.相等就结束了
			if (numbers[begin] + numbers[end] == target) {
				break;
			}
			// 2.两数结果 < target
			else if (numbers[begin] + numbers[end] < target) {
				begin++;
			}
			// 2.两数结果 > target
			else if (numbers[begin] + numbers[end] > target) {
				end--;
			}
		}

		int nums[] = { begin + 1, end + 1 };
		return nums;
	}


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

【LeetCode】167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that the...

167. Two Sum II - Input array is sorted (在有序数组中确定和为给定值的两个元素的下标)

Given an array of integers that is already sorted in ascending order, find two numbers such that the...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

[leetcode] 167. Two Sum II - Input array is sorted

[leetcode] 167. Two Sum II - Input array is sorted

【leetcode】167. Two Sum II - Input array is sorted

Difficulty:Medium Given an array of integers that is already sorted in ascending order, find two ...

LeetCode 167. Two Sum II - Input array is sorted

题目 : Given an array of integers that is already sorted in ascending order, find two numbers such th...

LeetCode 167:Two Sum II - Input array is sorted

排好序(升序)的一列数numbers,给定一个数key,求数列中是否存在两个数的和为给定的数key,若有则返回下标(从1开始,并不是0) 双指针问题,一个指向前部st,一个指向尾部etd。 那么分...

167. Two Sum II - Input array is sorted M

167. Two Sum II - Input array is sorted M

167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that the...

Leetcode 167. Two Sum II - Input array is sorted (Medium) (cpp)

167. Two Sum II - Input array is sorted (Medium)

[leetcode] 167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascend...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)