Update Leetcode 题解 - 哈希表.md
This commit is contained in:
parent
f84b140418
commit
4a56358678
@ -24,7 +24,7 @@
|
|||||||
可以先对数组进行排序,然后使用双指针方法或者二分查找方法。这样做的时间复杂度为 O(NlogN),空间复杂度为 O(1)。
|
可以先对数组进行排序,然后使用双指针方法或者二分查找方法。这样做的时间复杂度为 O(NlogN),空间复杂度为 O(1)。
|
||||||
|
|
||||||
用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i],如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。
|
用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i],如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。
|
||||||
|
|
||||||
```java
|
```java
|
||||||
public int[] twoSum(int[] nums, int target) {
|
public int[] twoSum(int[] nums, int target) {
|
||||||
HashMap<Integer, Integer> indexForNum = new HashMap<>();
|
HashMap<Integer, Integer> indexForNum = new HashMap<>();
|
||||||
@ -45,13 +45,19 @@ public int[] twoSum(int[] nums, int target) {
|
|||||||
|
|
||||||
[Leetcode](https://leetcode.com/problems/contains-duplicate/description/) / [力扣](https://leetcode-cn.com/problems/contains-duplicate/description/)
|
[Leetcode](https://leetcode.com/problems/contains-duplicate/description/) / [力扣](https://leetcode-cn.com/problems/contains-duplicate/description/)
|
||||||
|
|
||||||
|
|
||||||
```java
|
```java
|
||||||
public boolean containsDuplicate(int[] nums) {
|
public boolean containsDuplicate(int[] nums) {
|
||||||
Set<Integer> set = new HashSet<>();
|
Set<Integer> set = new HashSet<>();
|
||||||
for (int num : nums) {
|
for (int num : nums) {
|
||||||
set.add(num);
|
set.add(num);
|
||||||
|
//if set.containsKey(num){
|
||||||
|
// return true;
|
||||||
|
//}
|
||||||
|
//set.add(num);
|
||||||
}
|
}
|
||||||
return set.size() < nums.length;
|
return set.size() < nums.length;
|
||||||
|
//return false;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user