pull/38/head
jaredliw 2021-07-17 23:59:56 +08:00
parent 81dde48692
commit 8c4bcbbbe5
1 changed files with 107 additions and 11 deletions

View File

@ -18,13 +18,13 @@
> : [4,1,2,1,2]
> : 4
~
### HashMap
####
HashMap
HashMap
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/哈希表解法.1kefww8xsig0.png)
@ -39,7 +39,7 @@ class Solution {
}
//HashMap
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
//将其存入哈希表中含义为若该元素不存在则存入表中并计数为1若已经存在获取次数并加1.
//将其存入哈希表中含义为若该元素不存在则存入表中并计数为1若已经存在获取次数并加1
for (int x : nums) {
map.put(x , map.getOrDefault(x,0) + 1);
}
@ -48,13 +48,31 @@ class Solution {
if(map.get(y) == 1){
return y;
}
}
return 0;
}
}
}
```
```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
#
if len(nums) == 1:
return nums[0]
# HashMap
map_ = {}
# 11
for x in nums:
map_.setdefault(x, 0)
map_[x] += 1
# 1
for y, count in map_.items():
if count == 1:
return y
```
###
####
@ -65,6 +83,8 @@ class Solution {
####
Java Code:
```java
class Solution {
public int singleNumber(int[] nums) {
@ -74,9 +94,7 @@ class Solution {
//排序
Arrays.sort(nums);
for (int i = 1; i < nums.length-1; i+=2){
if (nums[i] == nums[i-1]){
continue;
}else{
if (nums[i] != nums[i-1]){
return nums[i-1];
}
}
@ -86,6 +104,21 @@ class Solution {
}
```
Python Code:
```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
#
nums.sort()
for i in range(1, len(nums), 2):
if nums[i] != nums[i - 1]:
return nums[i - 1]
return nums[len(nums) - 1]
```
### HashSet
@ -98,6 +131,8 @@ class Solution {
####
Java Code:
```java
class Solution {
public int singleNumber(int[] nums) {
@ -122,6 +157,26 @@ class Solution {
}
```
Python Code:
```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
set_ = set()
#
for x in nums:
#
if x in set_:
set_.remove(x)
#
else:
set_.add(x)
#
return set_.pop()
```
###
@ -147,11 +202,11 @@ class Solution {
stack.push(x);
continue;
}
//不同时直接跳出
//不同时直接跳出
if (stack.peek() != x) {
break;
}
//相同时出栈
//相同时出栈
stack.pop();
}
return stack.peek();
@ -159,6 +214,27 @@ class Solution {
}
```
Python Code:
```python
from collections import deque
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
nums.sort()
stack = deque()
for x in nums:
if not stack:
stack.append(x)
continue
if stack[-1] != x:
break
stack.pop()
return stack[-1]
```
###
@ -197,6 +273,14 @@ class Solution {
}
```
Python Code:
```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return 2 * sum(set(nums)) - sum(nums)
```
###
@ -221,6 +305,8 @@ class Solution {
####
Java Code:
```java
class Solution {
public int singleNumber(int[] nums) {
@ -234,4 +320,14 @@ class Solution {
}
```
Python Code:
```python
from functools import reduce
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda num, x: int(num) ^ int(x), nums)
```
6