LeetCode(二)关于TwoSum的实现

题目:

给定一个整数,从里面找出两个数,其和等于一个指定的整数。

程序返回这两个数在数组中的位置(数组下标从1开始),且位置小的在前面。

例如:数组 { 2, 7 , 11, 15}, 指定整数 = 9

返回:{1, 2}

Given an array of integers, 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

解题思路:

1)复制一个数组出来,并将复制出来的数组进行从小到大的排序。

2)指定排序后数组中的第一个数为第一个数,最后一个数为第二个数,可知第一个数是数组中最小的数,第二个数是数组中最大的数。

3)比较两个数的和(sum)跟指定的整数(target)的大小,如果 sum 小于 target,由于第二数已经是最大的数了,则说明第一个数太小,所以第一个数向前移。反之,如果 sum 大于 target,由于第一个数已经是最小的数了,则说明第二个数太大,所以第二个数要往后移。

4)重复进行第三步,直到两个数之后 sum 刚好等于指定的整数 target。

5)找出这两个数在原来数组中的位置,返回下标。

代码:

	public static int[] twoSum(int[] numbers, int target) {
		int[] result = new int[]{-1,-1};		
		int len = numbers.length;
		int[] sortedNumbers = new int[len];
		System.arraycopy(numbers, 0, sortedNumbers, 0, len);
		int first = 0;
		int second = len - 1;
		Arrays.sort(sortedNumbers);
		while(first < second){
			if(sortedNumbers[first] + sortedNumbers[second] < target){
				first++;
				continue;
			}
			if(sortedNumbers[first] + sortedNumbers[second] > target){
				second--;
				continue;
			}
			break;
		}
		int n1 = sortedNumbers[first];
		int n2 = sortedNumbers[second];
		
		for (int i = 0; i < len; i++) {
			if (n1 == numbers[i] || n2 == numbers[i]) {
				if (result[0] == -1) {
					result[0] = i + 1;
				} else {
					result[1] = i + 1;
					break;
				}
			}
		}
		
		return result;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值