leetcode - two-sum
文章目錄
- Q
- A - 1 暴力破解
- Q -2 查找表法
Q
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會(huì)對應(yīng)一個(gè)答案。但是,數(shù)組中同一個(gè)元素不能使用兩遍。
示例:
給定 nums = [2, 7, 11, 15], target = 9因?yàn)?nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]A - 1 暴力破解
枚舉數(shù)組中的每一個(gè)數(shù) x,尋找數(shù)組中是否存在 target - x
使用遍歷整個(gè)數(shù)組的方式尋找 target - x 時(shí),需要注意到每一個(gè)位于 x 之前的元素都已經(jīng)和 x 匹配過,因此不需要再進(jìn)行匹配。
而每一個(gè)元素不能被使用兩次,所以我們只需要在 x 后面的元素中尋找 target - x。
public class TwoSum {public static int[] twoSum(int[] nums, int target) {int len = nums.length ;for (int i = 0; i < len; i++) {for (int j = i+1 ; j < len ; j++){if (nums[i] + nums[j] == target){return new int[]{i,j};}}}return new int[0];}public static void main(String[] args) {int[] nums = new int[]{1,3,4,2};int target = 6;int[] targetArr = twoSum(nums, target);System.out.println(targetArr[0]);System.out.println(targetArr[1]);} }復(fù)雜度分析
時(shí)間復(fù)雜度:O(N^2),其中 N 是數(shù)組中的元素?cái)?shù)量。最壞情況下數(shù)組中任意兩個(gè)數(shù)都要被匹配一次。
空間復(fù)雜度:O(1) ,只用到了常數(shù)個(gè)變量
Q -2 查找表法
上面暴力破解的方法我們也看到了,時(shí)間復(fù)雜度 O(N^2) , 如何優(yōu)化呢?
通常都是使用 空間換時(shí)間
比如我們在遍歷的同時(shí),去記錄一些信息,為了是去掉一層循環(huán)。 那如果要記錄已經(jīng)遍歷的數(shù)值和它對應(yīng)的下標(biāo), 可以借助查找表發(fā)來實(shí)現(xiàn)。
常用的查找表的兩個(gè)實(shí)現(xiàn)是
因?yàn)檫@里沒有排序的需求,所以使用哈希表即可。
public static int[] twoSum2(int[] nums, int target) {int len = nums.length;Map<Integer, Integer> map = new HashMap<Integer, Integer>(len - 1);for (int i = 0; i < len; i++) {int another = target - nums[i] ;if (map.containsKey(another)){return new int[]{map.get(another),i};}map.put(nums[i], i);}return new int[0];}遍歷數(shù)組 nums,i 為當(dāng)前下標(biāo),每個(gè)值都判斷map中是否存在 target-nums[i] 的 key 值;
如果存在則找到了兩個(gè)值,如果不存在則將當(dāng)前的 (nums[i],i) 存入 map 中,繼續(xù)遍歷直到找到為止
復(fù)雜度分析
時(shí)間復(fù)雜度:O(N),其中 NN 是數(shù)組中的元素?cái)?shù)量。對于每一個(gè)元素 x,我們可以 O(1)地尋找 target - x。
空間復(fù)雜度:O(N),其中 NN 是數(shù)組中的元素?cái)?shù)量。主要為哈希表的開銷。
總結(jié)
以上是生活随笔為你收集整理的leetcode - two-sum的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache ZooKeeper - 选
- 下一篇: Apache ZooKeeper - J