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].
個人代碼數組
public int[] twoSum(int[] nums, int target) { //找出最值肯定堆大小 int min = nums[0], max = nums[0]; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; } else if (nums[i] < min) { min = nums[i]; } } String heap[] = new String[max - min + 1]; for (int i = 0; i < heap.length; i++) { heap[i] = ""; } //遍歷nums , 初始化堆 存放nums下標i for (int i = 0; i < nums.length; i++) { if (heap[nums[i] - min] == "") { heap[nums[i] - min] = "" + i; } else { heap[nums[i] - min] = heap[nums[i] - min] + "," + i; } } int result[] = new int[2]; //遍歷堆 for (int i = 0; i < heap.length; i++) { if (heap[i] != "" && (target - i - 2 * min) < heap.length && heap[target - i - 2 * min] != "") { if (heap[i].contains(",")) { String[] split = heap[i].split(","); result[0] = Integer.valueOf(split[0]).intValue(); result[1] = Integer.valueOf(split[1]).intValue(); break; } else { result[0] = Integer.valueOf(heap[i]).intValue(); result[1] = Integer.valueOf(heap[target - i - 2 * min]).intValue(); break; } } } return result; }
初始化一個堆,好比數組a【1,2,7,11】找9, 那麼會初始化一個11長度的數組b,對於輸入數組12711, 標記 b對應下標爲127 11的值分別爲0,1,2,3(即在a數組中的下標)。 而後遍歷b, 只要一個數和他相對於9的差數都被標記過,好比2,7直接返回兩個下標便可。
調試過程當中發現了重數{3,3},負數等狀況, 作了一些調整。
複雜度: 時間O(n) 空間O(n)測試
9ms 優於75% (cn站成績是8ms,優於92% 說明總站可能樣本什麼更全一些,故之後都在總站提交)調試
二次循環hash表,解決暴力方法中過多遍歷的問題,而且節省大量空間。
第一遍初始化hash表,
第二遍匹配。code
經過2,能夠看見能夠同時初始化與匹配,匹配中即返回,不然繼續初始化。
一次遍歷便可。ci
2.3的代碼見官網https://leetcode.com/problems/two-sum/solution/element
3理論上已是最優的了,耗時6ms,可是我發現官網居然還有更吊的leetcode
class Solution { public int[] twoSum(int[] nums, int target) { int t=4096; int bitMode=t-1; int[] temp=new int[t]; int length=nums.length; int firstValue=nums[0]; for(int i=1;i<length;i++){ int different=target-nums[i]; int current=nums[i]; if(different==firstValue) { return new int[] {0,i}; } int differentIndex=temp[different&bitMode]; if(differentIndex!=0){ return new int[] {differentIndex,i}; } int currentIndex=current&bitMode; temp[currentIndex]=i; } return null; } }
這個使用了位與來模擬,
可是我使用該數據測試,發現該解法是錯的。
int nums[] = {-1,0,1,2, 4097, 8193};
int target = 8194;get