您的位置:首页 > 其它

LeetCode.169(229) Majority Element && II

2017-10-23 19:35 459 查看
题目169:

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.
分析1(推荐):
class Solution {
public int majorityElement(int[] nums) {
//给定数组,找出其中多数(出现次数超过半数[n/2]向下取整),数组可以假设为空,多数一定存在的情况
//最佳算法:使用Moore’s voting algorithm,使用一个下标记录对比的数,相同+1,不同-1
//当记数为0时,另选择当前下标的为新的对比数
int curIndex=0,count=1;
for(int i=1;i<nums.length;i++){
//对比
if(nums[i]==nums[curIndex]){
count++;
}else{
count--;
}

//判断是count是否为0
if(count==0){
curIndex=i;
count=1;
}
}
return nums[curIndex];

}
}
分析2(原创):

class Solution {
public int majorityElement(int[] nums) {
//给定数组,找出其中出现频率最高的数(出现次数[n/2]向下取整),数组不为空,最高频率的数一定存在
if(nums.length==0||nums==null)return 0;

HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
int maxIndex=0;
for(int i=0;i<nums.length;i++){
if(hm.containsKey(nums[i])){
//包含相同数,频数+1
int oldValue=hm.get(nums[i]);
int newValue=oldValue+1;
if(newValue>hm.get(nums[maxIndex])){
maxIndex=i;
}

hm.put(nums[i],newValue);
}else{
//不包含
hm.put(nums[i],1);
}
}
//返回结果
return nums[maxIndex];
}
}

题目229:
Given an integer array of size n,
find all elements that appear more than 
⌊ n/3 ⌋
 times.
The algorithm should run in linear time and in O(1) space.

分析1(推荐-原创):

class Solution {
public List<Integer> majorityElement(int[] nums) {
//给定数组,找出所有出现次数大于n/3的数
int len =nums.length/3;

List<Integer> list =new ArrayList<>();

if(nums.length==0||nums==null){
return list;
}

Arrays.sort(nums);
int count=1;

if(nums.length==1){
list.add(nums[0]);
}else{
for(int i=1;i<nums.length;i++){
if(nums[i]==nums[i-1]){
//相等
count++;
}else{
if(count>len){
list.add(nums[i-1]);
}
//重置
count=1;
}

if(i==nums.length-1){
//最后一个,直接判断是否满足条件添加
if(count>len){
list.add(nums[i]);
}
}

}
}

return list;
}
}

分析2(原创):
class Solution {
public List<Integer> majorityElement(int[] nums) {
//给定数组,找出所有出现次数大于n/3的数
List<Integer> list=new ArrayList<>();
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
int len=nums.length/3;

if(nums.length==0||nums==null){
return list;
}

for(int i=0;i<nums.length;i++){
if(hm.containsKey(nums[i])){
int oldValue=hm.get(nums[i]);
hm.put(nums[i],oldValue+1);
}else{
hm.put(nums[i],1);
}
}

Set<Integer> set=hm.keySet();
for(Integer key:set){
Integer value=hm.get(key);
if(value>len){
list.add(key);
}
}

return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: