my solution in java


  • 0
    P
    public class Solution {
        public int majorityElement(int[] nums) {
            Arrays.sort(nums);
            int count = 1;
            int length = nums.length - 1;
            if (length == 0) {
                return nums[0];
            } else {
                while (length > 0) {
                    if (nums[length - 1] == nums[length]) {
                        count++;
                    } else {
                        if (count > nums.length / 2) {
                            break;
                        }
                        count = 1;
                    }
                    length--;
                }
                return nums[length + 1];
            }
        }
    }

  • 0
    T
    public int majorityElement(int[] nums) {
            Arrays.sort(nums);
            return nums[nums.length / 2];
    }
    

Log in to reply
 

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