問題の説明
配列内の数値の出現回数が配列の長さの半分を超えています。この数値を確認してください。
入力の説明:
配列を入力します
出力の説明:
発生数の半分以上を出力します
例
例1
[1,2,3,2,2,2,5,4,2]と入力します
出力
2
ソリューション
分析
- ハッシュ方式を使用します。
- 最初のトラバーサルで最も多く発生した数を見つけ、2番目のトラバーサルでその数の発生数を数えます
方法
- 統計の発生数を格納するhashMapを使用して、hashメソッドを使用し、条件を満たす数が見つかった場合は、
- 最初のトラバーサルで最も多く発生した数を見つけ、2番目のトラバーサルでその数の発生数を数えます
コード
// 思路1
public class Solution {
public int MoreThanHalfNum_Solution(int[] array) {
Map<Integer, Integer> temp = new HashMap<>();
int count = array.length / 2 + 1;
for (int i = 0; i < array.length; i++) {
if (temp.containsKey(array[i])) {
int tempCount = temp.get(array[i]);
tempCount++;
if (tempCount >= count) {
return array[i];
}
temp.put(array[i], tempCount);
} else {
temp.put(array[i], 1);
}
}
for (Map.Entry<Integer, Integer> entry : temp.entrySet()) {
if (entry.getValue() >= count) {
return entry.getKey();
}
}
return 0;
}
}
時間計算量分析:
O(N):配列をトラバースする回数はNであり、マップをトラバースする最大回数もNであるため、時間計算量はO(N)です。
空間の複雑さの分析:
O(N):配列に繰り返しの数値がないと仮定すると、マップにはすべての数値の出現回数が格納されるため、空間の複雑さはO(N)になります。
// 思路2
public class Solution {
public int MoreThanHalfNum2(int[] array) {
// 找出出现次数最多的数字
int res = array[0];
int count = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == res) {
count++;
} else {
count--;
}
if (count == 0) {
res = array[i];
count = 1;
}
}
count = 0;
// 遍历统计出现次数最多的数字的次数
for (int i = 0; i < array.length; i++) {
if (res == array[i]) {
count++;
}
}
// 判断次数是否达标
if (count > array.length / 2) {
return res;
}
return 0;
}
}
時間計算量分析:
O(N):配列を2回トラバースする回数は2Nであるため、時間計算量はO(N)です。
スペースの複雑さの分析:
O(1):余分なスペースは使用されません
テストしたい場合は、Niuke.comのリンクに直接アクセスしてテストを行うことができます