. [Swift] LeetCode1150 check whether a majority in number of the array | Check If a Number Is Majority Element in a Sorted Array

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤ micro-channel public number: to dare (WeiGanTechnologies)
➤ blog Park address: San-ching Wing Chi ( https://www.cnblogs.com/strengthen/ )
➤GitHub address: https://github.com/strengthen/LeetCode
➤ original address: HTTPS: //www.cnblogs. com / strengthen / p / 11333853.html 
➤ If the address is not a link blog Park Yong Shan Chi, it may be crawling author of the article.
➤ text has been modified update! Click strongly recommended that the original address read! Support authors! Support the original!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element.

majority element is an element that appears more than N/2 times in an array of length N

Example 1:

Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
Output: true
Explanation: 
The value 5 appears 5 times and the length of the array is 9.
Thus, 5 is a majority element because 5 > 9/2 is true.

Example 2:

Input: nums = [10,100,101,101], target = 101
Output: false
Explanation: 
The value 101 appears 2 times and the length of the array is 4.
Thus, 101 is not a majority element because 2 > 4/2 is false. 

Note:

  1. 1 <= nums.length <= 1000
  2. 1 <= nums[i] <= 10^9
  3. 1 <= target <= 10^9

To give the array a non-arrayed in descending order  nums, and a target value  target. If the array  nums values in most elements are equal  target, then return  True, otherwise return  False.

The so-called majority, refers to the length  N appears to be more than the array  N/2 times. 

Example 1:

Input: nums = [2,4,5,5,5,5,5,6,6], target = 5 
Output: true 
interpretation: 
number 5 occurred five times, the length of the array of 9. 
So, the vast majority of the 5 array, because five times> 9/2.

Example 2:

Input: nums = [10,100,101,101], target = 101 
Output: false 
interpretation: 
number 101 appears twice, the length of the array is 4. 
So, instead of an array of 101 elements of the majority, because 2 = 4/2. 

prompt:

  1. 1 <= nums.length <= 1000
  2. 1 <= nums[i] <= 10^9
  3. 1 <= target <= 10^9

28 ms

 1 class Solution {
 2     func isMajorityElement(_ nums: [Int], _ target: Int) -> Bool {
 3         var cnt:Int = 0
 4         for x in nums
 5         {
 6             if x == target
 7             {
 8                 cnt += 1
 9             }
10         }
11         return cnt > nums.count/2        
12     }
13 }

 

Guess you like

Origin www.cnblogs.com/strengthen/p/11333853.html