[Swift]LeetCode1150. 检查一个数是否在数组中占绝大多数 | Check If a Number Is Majority Element in a Sorted Array

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rqesatky-kq.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

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

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:app

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

给出一个按 非递减 顺序排列的数组 nums,和一个目标数值 target。假如数组 nums 中绝大多数元素的数值都等于 target,则返回 True,不然请返回 Falsespa

所谓占绝大多数,是指在长度为 N 的数组中出现必须 超过 N/2 次。 code

示例 1:htm

输入:nums = [2,4,5,5,5,5,5,6,6], target = 5
输出:true
解释:
数字 5 出现了 5 次,而数组的长度为 9。
因此,5 在数组中占绝大多数,由于 5 次 > 9/2。

示例 2:blog

输入:nums = [10,100,101,101], target = 101
输出:false
解释:
数字 101 出现了 2 次,而数组的长度是 4。
因此,101 不是 数组占绝大多数的元素,由于 2 次 = 4/2。 

提示:

  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 }