给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
思路:
(1)暴力解法。对于任意num in nums[],遍历数组查找能否构成target;复杂度为O(n2)
(2)两头齐头并进。首先先进行排序,然后 若最左+最右>target,左边指针向右移动;反之向左移动;复杂度O(nlogn)
(3)map映射法。首先将nums[]存入map中,然后遍历nums,查找target的差值
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.IntStream;
import javax.lang.model.type.PrimitiveType;
import javax.print.attribute.standard.PrinterLocation;
import org.omg.CORBA.ORBPackage.InconsistentTypeCode;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws FileNotFoundException {
Solution solution = new Solution();
int nums[] = { 7, 2, 9, 11 };
int result[] = solution.twoSumMap(nums, 13);
for (int i = 0; i < result.length; ++i) {
System.out.println(result[i]);
}
}
}
class Solution {
class ArrayHelper {
private int index;
private int value;
public ArrayHelper(int index, int value) {
this.index = index;
this.value = value;
}
}
public int[] twoSum(int[] nums, int target) {
int num1, num2;
for (int i = 0; i < nums.length; ++i) {
num1 = nums[i];
for (int j = i + 1; j < nums.length; ++j) {
num2 = nums[j];
if (num1 + num2 == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
public int[] twoSumNLogN(int[] nums, int target) {
int length = nums.length;
ArrayHelper[] helpers = new ArrayHelper[length];
for (int i = 0; i < length; ++i) {
helpers[i] = new ArrayHelper(i, nums[i]);
}
Arrays.sort(helpers, new Comparator<ArrayHelper>() {
@Override
public int compare(ArrayHelper o1, ArrayHelper o2) {
if (o1.value > o2.value) {
return 1;
}
// TODO Auto-generated method stub
else {
return -1;
}
}
});
for (int left = 0, right = length - 1; left < right;) {
while (helpers[left].value + helpers[right].value > target) {
--right;
}
while (helpers[left].value + helpers[right].value < target) {
++left;
}
if (helpers[left].value + helpers[right].value == target) {
return new int[] { helpers[left].index, helpers[right].index };
}
}
return new int[] {};
}
public int[] twoSumMap(int[] nums, int target) {
int length = nums.length;
int subtraction;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < length; ++i) {
map.put(nums[i], i);
}
for (int j = 0; j < length; ++j) {
subtraction = target - nums[j];
if (map.containsKey(subtraction) && map.get(subtraction) != j)
{
return new int[]{j,map.get(subtraction)};
}
}
return new int[] {};
}
}