169. Majority Element

Easy

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
package leetcode.easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random; public class MajorityElement {
@org.junit.Test
public void test() {
int[] nums1 = { 3, 2, 3 };
int[] nums2 = { 2, 2, 1, 1, 1, 2, 2 };
System.out.println(majorityElement1(nums1));
System.out.println(majorityElement1(nums2));
System.out.println(majorityElement2(nums1));
System.out.println(majorityElement2(nums2));
System.out.println(majorityElement3(nums1));
System.out.println(majorityElement3(nums2));
System.out.println(majorityElement4(nums1));
System.out.println(majorityElement4(nums2));
System.out.println(majorityElement5(nums1));
System.out.println(majorityElement5(nums2));
System.out.println(majorityElement6(nums1));
System.out.println(majorityElement6(nums2));
} public int majorityElement1(int[] nums) {
int majorityCount = nums.length / 2; for (int num : nums) {
int count = 0;
for (int elem : nums) {
if (elem == num) {
count += 1;
}
} if (count > majorityCount) {
return num;
}
} return -1;
} private Map<Integer, Integer> countNums(int[] nums) {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (int num : nums) {
if (!counts.containsKey(num)) {
counts.put(num, 1);
} else {
counts.put(num, counts.get(num) + 1);
}
}
return counts;
} public int majorityElement2(int[] nums) {
Map<Integer, Integer> counts = countNums(nums); Map.Entry<Integer, Integer> majorityEntry = null;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {
majorityEntry = entry;
}
} return majorityEntry.getKey();
} public int majorityElement3(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
} 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 majorityElement4(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;
}
}
} private int countInRange(int[] nums, int num, int lo, int hi) {
int count = 0;
for (int i = lo; i <= hi; i++) {
if (nums[i] == num) {
count++;
}
}
return count;
} private int majorityElementRec(int[] nums, int lo, int hi) {
// base case; the only element in an array of size 1 is the majority
// element.
if (lo == hi) {
return nums[lo];
} // recurse on left and right halves of this slice.
int mid = (hi - lo) / 2 + lo;
int left = majorityElementRec(nums, lo, mid);
int right = majorityElementRec(nums, mid + 1, hi); // if the two halves agree on the majority element, return it.
if (left == right) {
return left;
} // otherwise, count each element and return the "winner".
int leftCount = countInRange(nums, left, lo, hi);
int rightCount = countInRange(nums, right, lo, hi); return leftCount > rightCount ? left : right;
} public int majorityElement5(int[] nums) {
return majorityElementRec(nums, 0, nums.length - 1);
} public int majorityElement6(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_169. Majority Element的更多相关文章

  1. [LeetCode] Majority Element II 求众数之二

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...

  2. [LeetCode] Majority Element 求众数

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  3. 【leetcode】Majority Element

    题目概述: Given an array of size n, find the majority element. The majority element is the element that ...

  4. ✡ leetcode 169. Majority Element 求出现次数最多的数 --------- java

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  5. (Array)169. Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  6. LeetCode 169. Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  7. [UCSD白板题] Majority Element

    Problem Introduction An element of a sequence of length \(n\) is called a majority element if it app ...

  8. Leetcode # 169, 229 Majority Element I and II

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  9. LeetCode【169. Majority Element】

    Given an array of size n, find the majority element. The majority element is the element that appear ...

随机推荐

  1. Windows 对外开放端口号

    前记 今天在做 Kafka 消息传输时,本地连接服务器的 Kafka 出现问题.连接不上,想到新的服务器应该是防火墙关闭所致. 我呢,就用了最直接暴力的方法:关闭防火墙~~~~(哈哈哈) 问题是解决了 ...

  2. Postgresql Useful SQL/Commands

    Update records ' and a.subscriber_id=b.subscriber_id; Connections select count(*) from pg_stat_activ ...

  3. 你所不知道的printf函数

    #include <stdio.h> int main(void) { int a = 4; int b = 3; int c = a / b; float d = *(float *)( ...

  4. canvas小球动画

    绘制小球 我们将会画一个小球用于动画学习,所以首先在画布上画一个球.下面的代码帮助我们建立画布. <canvas id="></canvas> 跟平常一样,我们需要先 ...

  5. [GraphQL] Reuse GraphQL Selection Sets with Fragments

    Fragments are selection sets that can be used across multiple queries. They allow you to refactor re ...

  6. HTML 009 CSS

    HTML 样式- CSS CSS (Cascading Style Sheets) 用于渲染HTML元素标签的样式.     Look! Styles and colors Manipulate Te ...

  7. sql server update 的批量更新方法

    假定我们有两张表,一张表为Product表存放产品信息,其中有产品价格列Price:另外一张表是ProductPrice表,我们要将ProductPrice表中的价格字段Price更新为Price表中 ...

  8. C++构造函数的default和delete

    C++11中,当类中含有不能默认初始化的成员变量时,可以禁止默认构造函数的生成, myClass()=delete;//表示删除默认构造函数 myClass()=default;//表示默认存在构造函 ...

  9. 节点(node)操作

    一.节点的属性 节点值页面中的所有内容,包括标签.属性.文本 nodeType,节点类型:如果是标签,则是1:如果是属性.则是2:如果是文本,则是3 nodeName,节点名字:如果是标签,则是大写的 ...

  10. tarjan模板完整版

    https://www.luogu.org/problem/P2863 #include<cstdio> #include<vector> using namespace st ...