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. 如果一個數組里某個元素出現的次數超過總數的一半,那么,就把這個元素稱為優先元素,找到這個元素。
看到題目的第一想法是遍歷,讀取每個元素出現的次數,然后選取出現次數最多的那個。然后想想,這樣的話優先元素超過總數一半的條件不就沒什么用,如果把整個數組排個序,在有序條件下某個元素出現次數超過一半,那么中位數不就是優先元素嗎。 想通了思路,編碼就很簡單。
public int majorityElement(int[] nums) { Arrays.sort(nums); int len = nums.length; if(len%2 == 0) return nums[len/2]; else return nums[(len-1)/2]; }新聞熱點
疑難解答