一、題目說(shuō)明
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].
查看原題;
查看我的Github項(xiàng)目地址;
題目很簡(jiǎn)單:給定一個(gè)int數(shù)組和一個(gè)目標(biāo)值刁笙,返回?cái)?shù)組中兩個(gè)數(shù)之和等于目標(biāo)值的這兩個(gè)數(shù)的索引声搁。
二瞭稼、解題
2.1 窮舉法
這是首先想到的方法,也是最簡(jiǎn)單直接的方法。
遍歷所有兩個(gè)數(shù)之和裁良,找到等于目標(biāo)值的兩個(gè)數(shù)即可。
代碼如下:
public static int[] twoSumByExhaustive(int[] arr, int target) {
int[] result = new int[2];
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
很多算法都可以用窮舉法解決校套,但是作為一個(gè)有理想有追求的程序猿价脾,怎可滿足于此。
2.2 以空間換時(shí)間
問(wèn):求兩個(gè)數(shù)之和等于目標(biāo)值有其他的描述方式么笛匙?
答:有侨把,也可以說(shuō)是求目標(biāo)值和其中一個(gè)數(shù)之差在數(shù)組中的位置。
于是妹孙,很自然我們想到了以空間換取時(shí)間秋柄,用HashMap存儲(chǔ)之差,然后循環(huán)數(shù)組找到等于差的數(shù)蠢正。
代碼如下:
public static int[] twoSumByMap(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
result[0] = map.get(nums[i]);
result[1] = i;
} else {
map.put(target - nums[i], i);
}
}
return result;
}
2.3 排序后再查找
問(wèn):假如數(shù)組是有序的骇笔,那么是不是可以更快的找到結(jié)果?
答:如果是有序數(shù)組,那就可以一趟循環(huán)二路查找結(jié)果笨触,自然更快懦傍。
但是這會(huì)有幾個(gè)問(wèn)題:
1.排序的消耗?
可以采用快排等高性能排序算法
2.排序后如何返回正確的索引芦劣?
可以HashMap存鍵值對(duì)粗俱,然后查找索引。但是如果鍵是相同的數(shù)虚吟,索引就會(huì)出錯(cuò)源梭。
可以copy一份原數(shù)組,查找索引稍味。
代碼如下:
public static int[] twoSumBySort(int[] nums, int target) {
int[] result = new int[2];
// int[] copyNums = nums.clone();
int[] copyNums = new int[nums.length];
System.arraycopy(nums, 0, copyNums, 0, nums.length);
// 可以自己寫排序算法
Arrays.sort(nums);
int sIndex = 0;
int eIndex = nums.length - 1;
for (int i = 0; i < nums.length; i++) {
if (nums[sIndex] + nums[eIndex] == target) {
result[0] = nums[sIndex];
result[1] = nums[eIndex];
break;
} else if (nums[sIndex] + nums[eIndex] > target) {
eIndex--;
} else {
sIndex++;
}
}
boolean fGit = false;
for (int i = 0; i < copyNums.length; i++) {
if (!fGit && copyNums[i] == result[0]) {
sIndex = i;
fGit = true;
} else if (copyNums[i] == result[1]) {
eIndex = i;
}
}
if (sIndex > eIndex) {
result[0] = eIndex;
result[1] = sIndex;
} else {
result[0] = sIndex;
result[1] = eIndex;
}
return result;
}