力扣算法
1 兩數之和
給定一個整數數組nums和一個整數目標值target,請你在數組中找出和為目標值target的那兩個整數,返回他們的數組下標。
(1)暴力枚舉
(枚舉數組每一個數x,再尋找數組中是否存在 target -x)
public int[] twoSum(int[] nums,int target) {int n = nums.length;for (int i = 0; i<n; ++i) {for(int j = i + 1; j < n;++j) {if (nums[i] + nums[j] == target) {return new int[]{i,j};}}}
return new int[0];
}
(2)哈希表
對于每個x,我們查詢哈希表中是否存在target-x,將x插入哈希表中
public int[] twoSum(int[] nums,int target) {Map<Integer,Integer> hashTable = new HashMap();for(int i = 0;i<nums.length;++i) {if(hashTable.containsKey(target-nums[i])){return new int[] {hashTable.get(target-nums[i]),i}; //返回當前x的數組索引和哈希表中匹配的數組索引值} hashTable.put(nums[i],i);}return new in[0];
}
2 無重復字符的最長子串
3 二叉樹的前序遍歷