• 229. Majority Element II java solutions


    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.

    Hint:

    1. How many majority elements could it possibly have?
    2. Do you have a better hint? Suggest it!

    Subscribe to see which companies asked this question

     1 public class Solution {
     2     public List<Integer> majorityElement(int[] nums) {
     3         List<Integer> ans = new ArrayList<Integer>();
     4         if(nums.length <= 0) return ans;
     5         Arrays.sort(nums);
     6         int i = 0,len = nums.length,tmp = 0;
     7         while(i < len - len/3){
     8             if(nums[i] == nums[i+len/3]){
     9                 tmp = nums[i];
    10                 ans.add(tmp);
    11                 i += len/3;
    12                 while(i < len - len/3 && nums[i] == tmp)i++;
    13             }else i++;
    14         }
    15         return ans;
    16     }
    17 }

    解法二:

    可用一个hashmap 来计算元素出现个数,但是超过space O(1) 的限制。

    解法三:

    https://discuss.leetcode.com/topic/32510/java-easy-version-to-understand/2 二刷在研究。

  • 相关阅读:
    多线程实践
    sql你server,mysql,oracle的分页语句
    BS与CS的联系与区别
    EJB与JAVA BEAN的区别
    Struts2.0 xml文件的配置(package,namespace,action)
    Q 51~60
    Q 41~50
    列表推导式
    Q 31~40
    Q 21~30
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5644388.html
Copyright © 2020-2023  润新知