# 169. Majority Element > ***View the book with <i class="fa fa-book"></i> Book Mode.*** - [**LeetCode筆記目錄**](https://hackmd.io/@WeiYee/SyABdj_eA) ## :book: 題目 **網址:** https://leetcode.com/problems/majority-element/description/ ## :dart: 解題步驟 - 因為眾數的數量大於一半,所以假設遇到眾數 +1,其他數字 -1,其結果一定為非負整數。 - 遍歷 nums,i 為當前基準,j 為當前處理的位置,times 為 - 若 nums[j] == nums[i],+1,反之 -1 - 倘若結果為負,i 變成 j - 1,並繼續判斷 - 遍歷完後,nums[i] 即為眾數 ## :pencil2: 程式碼 ### Java ```java= class Solution { public int majorityElement(int[] nums) { for (int i = 0; i < nums.length; ++i) { int times = 1; int curr = nums[i]; for (int j = i + 1; j < nums.length; ++j) { if (curr == nums[j]) ++times; else --times; if (times < 0) { i = j - 1; break; } } if (times > 0) return curr; } return -1; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up