This commit is contained in:
jaredliw 2021-07-17 23:59:56 +08:00
parent 81dde48692
commit 8c4bcbbbe5

View File

@ -18,7 +18,7 @@
> 输入: [4,1,2,1,2]
> 输出: 4
这个题目非常容易理解就是让我们找出那个只出现一次的数字那么下面我们来看一下这几种解题方法吧
这个题目非常容易理解就是让我们找出那个只出现一次的数字那么下面我们来看一下这几种解题方法吧~
### HashMap
@ -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);
}
@ -49,12 +49,30 @@ class Solution {
return y;
}
}
return 0;
}
}
```
```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# 特殊情况
if len(nums) == 1:
return nums[0]
# HashMap
map_ = {}
# 将其存入哈希表中含义为若该元素不存在则存入表中并计数为1若已经存在获取次数并加1
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()
```
###
@ -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种解题方法肯定还有别的方法欢迎大家讨论大家可以在做题的时候一题多解这样能大大提高自己解题能力下面我们来看一下这些方法如何应用到其他题目上