leetcode-169.求众数
生活随笔
收集整理的這篇文章主要介紹了
leetcode-169.求众数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
題目:
給定一個大小為?n?的數(shù)組,找到其中的眾數(shù)。眾數(shù)是指在數(shù)組中出現(xiàn)次數(shù)大于?? n/2 ??的元素。
你可以假設(shè)數(shù)組是非空的,并且給定的數(shù)組總是存在眾數(shù)。
示例?1:
輸入: [3,2,3] 輸出: 3示例?2:
輸入: [2,2,1,1,1,2,2] 輸出: 2答案:
class Solution {// 眾數(shù)求解算法public int majorityElement(int[] nums) {// 黑板(用于記錄數(shù)據(jù)用)LinkedHashMap<Integer, Integer> blackboard = new LinkedHashMap<>();// 左邊記錄到的位置int leftPs = 0;// 右邊記錄到的位置int rightPs = nums.length - 1;// 眾數(shù)Integer mode = null;tag: while (leftPs <= rightPs) {for (int i = leftPs; i <= rightPs; i++) {if (blackboard.get(nums[i]) == null) {blackboard.put(nums[i], 1);leftPs = i + 1;if (leftPs > rightPs) {mode = nums[i];}break;} else {int count = blackboard.get(nums[i]);count++;if (count>nums.length/2) {mode = nums[i];break tag;}blackboard.put(nums[i], count);}}for (int i = rightPs; i >= leftPs; i--) {if (blackboard.get(nums[i]) == null) {blackboard.put(nums[i], 1);rightPs = i - 1;if (rightPs < leftPs) {mode = nums[i];}break;} else {int count = blackboard.get(nums[i]);count++;if (count>nums.length/2) {mode = nums[i];break tag;}blackboard.put(nums[i], count);}}}return mode;} }?
轉(zhuǎn)載于:https://www.cnblogs.com/Grace-is-enough/p/9116016.html
總結(jié)
以上是生活随笔為你收集整理的leetcode-169.求众数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「shell」替代rm,放入回收站
- 下一篇: 小程序之点击跳转到对应内容