一、題目描述
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, and you may not use the same element twice.
給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
二、解題思路
我的第一感覺就是用暴力法,簡單直接。在一個數組中找到二個數字,它們的和爲目標值的和。二重循環,只要第二重循環中只要存在target-nums[i]的數值,而且此值的下標不爲i。返回這二個值(i , target-nums[i]的下標)。但是此解法的時間複雜度爲O(n^2)。
有一種時間複雜度比較低一點的,用哈希表,整體思想也是和暴力類類似。將數組表示的數據,用哈希表表示,將數據的值和下標聯繫起來,循環遍歷數組的每一個元素,然後查看哈希表中是否存在target-nums[i]的數值且此值的下標不爲i。
還有一種更優秀一點的思想。同樣是用哈希表,不過只遍歷一次數組。每取一個nums[i],就判斷target-nums[i]是不是再哈希表中,當然一開始哈希表中的數值爲空。如果有就返回二個值的下標。沒有執行下一個操作,將nums[i]加入到和哈希表中。
三、代碼實現
package com.acm.Secondmonth;
import java.util.HashMap;
import java.util.Map;
public class LetCode001 {
public static void main(String[] args) {
int[] num = {3,3};
int target = 6;
int[] index = new int[2];
index = twoSum03(num , target);
for (int i : index) {
System.out.println(i);
}
}
private static int[] twoSum(int[] num, int target) {
int[] index = new int[2];
for(int i=0 ; i<num.length ; i++) {
index[0] = i;
for(int j=i ; j<num.length ; j++) {
if(target - num[i] == num[j]) {
index[1] = j;
return index;
}
}
}
return null;
}
private static int[] twoSum01(int[] nums, int target) {
//將值個下標聯繫起來
Map<Integer , Integer> map = new HashMap<>();
for(int i=0 ; i<nums.length ; i++) {
map.put(nums[i], i);
}
for(int i=0 ; i<nums.length ; i++) {
int complement = target - nums[i];
//和暴力法不同就是map有自帶的函數 看是不是包含target-nums[i] 同時 下標不一樣
//如果有 就返回該值
if(map.containsKey(complement) && map.get(complement) != i) {
return new int[] {i , map.get(complement)};
}
}
throw new IllegalArgumentException("No two sum solution!");
}
/**
* 一次遍歷
* @param nums
* @param target
* @return
*/
public static int[] twoSum03(int[] nums, int target) {
if(nums == null) {
throw new RuntimeException("invaild input:nums is empty!");
}
Map<Integer, Integer> map = new HashMap<>();
for(int i=0 ; i<nums.length ; i++) {
int complement = target - nums[i];
System.out.println(complement + " " + map.get(complement) + " " + nums[i]);
if(map.containsKey(complement) && map.get(complement) != i) {
return new int[]{i , map.get(complement)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution!");
}
}
作者:Rusian_Stand
來源:CSDN
原文:https://blog.csdn.net/Vpn_zc/article/details/84072492
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!