ほとんどの要素(シンプル):13日には169タイトルをLeetCode月パンチカードアクティビティ
- タイトル:サイズnのアレイを考えると、要素の大部分は、その中に見つかりました。配列内の要素のほとんどは、n / 2より⌊⌋大きい要素出現数を意味します。あなたは、配列が空であると仮定することができ、与えられた配列のほとんどの要素が常にあります。
- 問題解決のアイデア:HashMapを使用する最初の試み、非常に熟練したが、非常に満足して成功しました~~
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> hash = new HashMap<>();
hash.put(nums[0],1);
for(int i=1;i<nums.length;i++){
if(hash.containsKey(nums[i])){
hash.put(nums[i],hash.get(nums[i])+1);
}else{
hash.put(nums[i],1);
}
}
for(Map.Entry<Integer,Integer> entry:hash.entrySet()){
if(entry.getValue() > nums.length/2){
return entry.getKey();
}
}
return 0;
}
}
- 問題解決の練習1:配列をソートし、この方法は、あまりにも簡単です!!
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 問題解決アプローチ2:乱数の実施、多数のランダムな確率は、数値の範囲内です。
class Solution {
private int randRange(Random rand, int min, int max) {
return rand.nextInt(max - min) + min;
}
private int countOccurences(int[] nums, int num) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == num) {
count++;
}
}
return count;
}
public int majorityElement(int[] nums) {
Random rand = new Random();
int majorityCount = nums.length/2;
while (true) {
int candidate = nums[randRange(rand, 0, nums.length)];
if (countOccurences(nums, candidate) > majorityCount) {
return candidate;
}
}
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 問題解決のアプローチ3:投票アルゴリズムは非常に興味深いですが、私は長い時間のためだと思います。以下は、私の理解です。
整数変数として宣言集会の候補の数を選択して、アレイを介して、そして候補の数から-1の範囲、+1公衆に等しいです。そして公共の候補の選択数で0に等しいです。公共のための候補者の最終的な数は、会衆の実数です。
会衆の候補の数が本当にモード、最終的なもので、ゼロよりも大きくする必要がある場合。すべての候補者は1つが本当にAではないモードであり、2例に分けることができます。とき、それは本当に会衆の数、および状況変わらないか、0です。次の候補数は、実際に残りのすべてのランダムな、より少ない数のエミュレートされ、より容易にアクセスモードへ、0より大きく、最終でなければなりません。
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。