Given an array of sizen, 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.
這道題其實可以用比較取巧的方法做。因為在這里marjority element的定義是整個數列中至少一半的數字都是它,所以當我們sorting了整個數列,中間的那個數肯定是Marjority element。所以非常簡單,考慮下length為1的特殊情況就可。代碼如下。
public class Solution { public int majorityElement(int[] nums) { if(nums.length==1){ return nums[0]; } Arrays.sort(nums); return nums[nums.length/2]; }}
當然了還有比較常規的,老實按照loop來計算的。這個思路就很簡單了。代碼如下。
public class Solution { public int majorityElement(int[] num) { if(num.length==1){ return num[0]; } Arrays.sort(num); int test=num[0]; int count=1; for(int i=1; i<num.length; i++){ if(num[i] == test){ count++; if(count > num.length/2) return num[i]; }else{ count=1; test = num[i]; } } return 0; }}
新聞熱點
疑難解答