Two Sum

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

这个题目经常网上面试题中可以看到,但是如果想要通过OJ 特别需要注意一些特殊的测试案例。

题意说了肯定会有一组而且只有一组解,所以不要去担心无解的情况。 需要特别注意就是出现重复元素情况。如:[0 , 1, 2, 0] ,target = 0

则输出要是 index1=1, index2=4 所以在进行查找时需要进行标记,某个位置使用了就不能再选择啦!

package Two_Sum;

import java.util.Arrays;

public class Solution {
	public int[] twoSum(int[] numbers, int target) {
		int len = numbers.length;
		//只需要拷贝numbers 中数据,copy = numbers 表明copy 指向同一引用
		int[] copy = Arrays.copyOf(numbers, len);
		Arrays.sort(numbers);
		int[] ans = new int[2];
		for (int i = 0, j = len - 1; i < len && j >= i;) {
			if (numbers[i] + numbers[j] == target) {
				ans[0] = findPlace(numbers[i], copy, -1);
				ans[1] = findPlace(numbers[j], copy, ans[0] - 1);
				break;
			} else if (numbers[i] + numbers[j] > target) {
				j--;
			} else {
				i++;
			}
		}
		//调整最终坐标的位置。
		if (ans[0] > ans[1]) {
			int temp = ans[0];
			ans[0] = ans[1];
			ans[1] = temp;
		}
		return ans;
	}

	public int findPlace(int val, int[] num, int oPlace) {
		int place = 0;
		for (int i = 0; i < num.length; i++) {
			if (num[i] == val && i != oPlace) {
				place = i;
				break;
			}
		}
		return place + 1;
	}

	public static void main(String[] args) {
		int[] num = { 2,3,4,5,7,9,21,34,23};
		int target = 9;
		Solution s = new Solution();
		int[] ans = s.twoSum(num, target);
		System.out.println(ans[0]);
		System.out.println(ans[1]);
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值