目录
1. 两数之和(简单)
1.1. 题目描述
1.2. 解题思路
方法:哈希表(推荐使用)
2. 数组中出现次数超过一半的数字(简单)
2.1. 题目描述
2.2. 解题思路
方法:哈希表(推荐使用)
java实现代码:
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//哈希表统计每个数字出现的次数
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
//遍历数组
for(int i = 0; i < array.length; i++){
//统计频率
if(!mp.containsKey(array[i]))
mp.put(array[i], 1);
else
mp.put(array[i], mp.get(array[i]) + 1);
//一旦有个数大于长度一半的情况即可返回
if(mp.get(array[i]) > array.length / 2)
return array[i];
}
return 0;
}
}
3. 数组中只出现一次的两个数字(中等)
3.1. 题目描述
3.2. 解题思路
方法一:哈希表(推荐使用)
import java.util.*;
public class Solution {
public int[] FindNumsAppearOnce (int[] array) {
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
//遍历数组
for(int i = 0; i < array.length; i++)
//统计每个数出现的频率
if(!mp.containsKey(array[i]))
mp.put(array[i], 1);
else
mp.put(array[i], mp.get(array[i]) + 1);
//再次遍历数组
for(int i = 0; i < array.length; i++)
//找到频率为1的两个数
if(mp.get(array[i]) == 1)
res.add(array[i]);
//整理次序
if(res.get(0) < res.get(1))
return new int[] {res.get(0), res.get(1)};
else
return new int[] {res.get(1), res.get(0)};
}
}
方法二:异或运算(扩展思路)
Java实现代码:
import java.util.*;
public class Solution {
public int[] FindNumsAppearOnce (int[] array) {
int res1 = 0;
int res2 = 0;
int temp = 0;
//遍历数组得到a^b
for(int i = 0; i < array.length; i++)
temp ^= array[i];
int k = 1;
//找到两个数不相同的第一位
while((k & temp) == 0)
k <<= 1;
for(int i = 0; i < array.length; i++){
//遍历数组,对每个数分类
if((k & array[i]) == 0)
res1 ^= array[i];
else
res2 ^= array[i];
}
//整理次序
if(res1 < res2)
return new int[] {res1, res2};
else
return new int[] {res2, res1};
}
}
4. 缺失的第一个正整数(中等)
4.1. 题目描述
4.2. 解题思路
方法一:哈希表(推荐使用)
import java.util.*;
public class Solution {
public int m