leetcode--Majority Element
来源:互联网 发布:微信和前端知乎 编辑:程序博客网 时间:2024/05/03 01:11
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.
One : Sorting先排序,然后找major和count分别记录键值对count>n/2就返回major。
public class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); int major = nums[0]; int count = 1; for(int i = 1;i<nums.length;i++){ if(major==nums[i]){ count++; if(count>nums.length/2){ return major; } }else { count = 1; major = nums[i]; } } return major; }}Two:Sorting是one的优化
public int majorityElement1(int[] nums) { Arrays.sort(nums); return nums[nums.length/2];}
Three:Voting 投票机制。
public class Solution { public int majorityElement(int[] nums) { int major = nums[0]; int count = 1; for(int i = 1;i<nums.length;i++){ if(count==0){ count++; major = nums[i]; }else if(major == nums[i]) { count++; }else{ count--; } } return major; }}Four:利用HashMap来操作Hashtable
public class Solution { public int majorityElement(int[] nums) { Map<Integer,Integer> myMap = new HashMap<Integer,Integer>(); int ret = nums[0]; for(int num : nums){ if(!myMap.containsKey(num)){ myMap.put(num,1); }else{ myMap.put(num,myMap.get(num)+1); if(myMap.get(num)>nums.length/2){ ret = num; break; } } } return ret; }}Five:
// Bit manipulation public int majorityElement(int[] nums) { int[] bit = new int[32]; for (int num: nums) for (int i=0; i<32; i++) if ((num>>(31-i) & 1) == 1) bit[i]++; int ret=0; for (int i=0; i<32; i++) { bit[i]=bit[i]>nums.length/2?1:0; ret += bit[i]*(1<<(31-i)); } return ret;}
0 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- HDU:1556 Color the ball
- QMessageBox
- 深入理解Java:SimpleDateFormat安全的时间格式化
- 定位 DIV 技巧
- oracle常规操作
- leetcode--Majority Element
- CSS3 Transition 和Animation区别及比较
- 递归的理解
- 设置maven编译器级别
- Spring Boot的被@SpringBootApplication注解的App.java必须放在所有的RestController的根路径的package下
- js仿微信语音播放
- 进程间的通信方法
- 使用Visual Studio制作安装包
- JAVA学习40_ CentOS 7默认的jdk 1.7升级方法(到1.8) - alternatives的功能