盒子
盒子

Leetcode 1 Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.
Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

给一个整数数组(元素不重复)和一个整数,找出数组内的任意两个元素的索引,让这两个元素之和等于给出的整数。

package com;

import java.util.Arrays;

public class Code1 {

public static void main(String[] args) {
int[] numes = { 1, 2, 4, 6, 3, 8, 7, 9 };
int t = 12;
int[] res = twoSum(numes, t);
System.out.println(Arrays.toString(res));
}

public final static int[] twoSum(int[] nums, int target) {

int Length = nums.length;
int[] numsCopy = Arrays.copyOf(nums, Length);
Arrays.sort(numsCopy);

int num1 = 0;
int num2 = 0;
for (int i = 0, j = Length - 1, sum; i < j;) {
sum = numsCopy[i] + numsCopy[j];
if (sum == target) {
num1 = numsCopy[i];
num2 = numsCopy[j];
break;
}
if (sum > target) {
j--;
} else {
i++;
}
}

int[] result = new int[2];
for (int i = 0, j = 0; i < Length && j < result.length; i++) {
int mid = nums[i];
if (mid == num1 || mid == num2) {
result[j] = i;
j++;
}
}
return result;
}
}