[LeetCode]: 169: Majority Element
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode]: 169: Majority Element
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
?
思路:直接查找,使用arraylist記錄結果,出現超過一半的數就返回
?
代碼:
public class Solution {public static int bExist(ArrayList<int[]> nums,int intInput) {for(int i = 0;i<nums.size();i++){if( nums.get(i)[0]== intInput){return i;}}return -1;}public static int majorityElement(int[] nums) {ArrayList<int[]> arrResult = new ArrayList<int[]>();for(int i = 0;i<nums.length;i++){int intPos = bExist(arrResult,nums[i]);if( intPos == -1){int[] arrTemp = {nums[i],0};arrResult.add(arrTemp);}else{arrResult.get(intPos)[1] += 1; if(arrResult.get(intPos)[1] > (nums.length/2)){return arrResult.get(intPos)[0];}}}int intTemp = 0;int intPos = 0;for(int i = 0;i<arrResult.size();i++ ){if(intTemp <= arrResult.get(i)[1]){intTemp =arrResult.get(i)[1];intPos = i;}}return arrResult.get(intPos)[0];} }?
網上高人的思路:每找出兩個不同的element,則成對刪除。最終剩下的一定就是所求的。
代碼:
public static int majorityElement(int[] nums) {int candidate = 0;int count = 0;for(int i = 0; i < nums.length; i ++){if(count == 0){candidate = nums[i];count = 1;}else{if(nums[i] == candidate)count ++;elsecount --;}}return candidate;}?
轉載于:https://www.cnblogs.com/savageclc26/p/4830970.html
總結
以上是生活随笔為你收集整理的[LeetCode]: 169: Majority Element的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2015年秋季个人阅读计划
- 下一篇: No Team Selected:A t