Random agorithms in JAVA,3ms


  • 0
    M
    public class Solution {
        public int majorityElement(int[] nums) {
            for (int i=0;i<5;i++)
            {
                int v1=((int)(Math.random()*nums.length*10))%nums.length;
                if(isMajor(nums,nums[v1]))
                    return  nums[v1];
            }
            return  0;
    
        }
        public  boolean isMajor(int[] nums,int v)
        {
            int n=0;
            for (int i=0;i<nums.length;i++)
            {
                if(nums[i]==v)
                    n++;
            }
            return  n>nums.length/2;
            }
    
    }

  • 0
    T

    Good old pointless random algo, good idea for fun. It's funny that 5 tries are enough, do you have some math background for that?
    .
    Why do you multiply by 10 and then modulo? (int)(Math.random()*nums.length) alone should give a similarly distributed random index.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.