GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/src/MajorityElement.java at master · LeBW/leetcode Expand file tree/ Copy pathMajorityElement.javaMore file actions 40 lines (38 loc) · 1.12 KB / Copy pathMajorityElement.javaFile metadata and controls40 lines (38 loc) · 1.12 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import java.util.HashMap; import java.util.Map; /** * 169. Majority Element * @author LBW */ public class MajorityElement { public int majorityElement(int[] nums) { int n = nums.length; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); if (map.get(nums[i]) > (n / 2)) { return nums[i]; } } return -1; } /** * 摩尔投票法。原理:出现超过一半次数的元素,一定比其他所有元素加起来的个数都要多,因此candidate最终一定会指向出现超过一半次数的元素。 */ public int majorityElementTwo(int[] nums) { int n = nums.length; int candidate = nums[0], count = 0; for (int i = 0; i < nums.length; i++) { if (count == 0) { candidate = nums[i]; } if (nums[i] == candidate) { count += 1; } else { count -= 1; } } return candidate; } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |