leetCode 169. Majority Element 数组

简介:

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than  n/2  times.

You may assume that the array is non-empty and the majority element always exist in the array.


思路1:

使用map来处理。

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
class  Solution {
public :
     int  majorityElement(vector< int >& nums) {
         map< int int > record;
         for  ( int  i = 0; i < nums.size(); i++)
         {
             if  (record.find(nums[i]) == record.end())
             {
                 record.insert(pair< int int >(nums[i], 1));
                 if  (record[nums[i]] > nums.size() / 2)
                 {
                     return  nums[i];
                 }
             }
             else
             {
                 record[nums[i]] += 1;
                 if  (record[nums[i]] > nums.size() / 2)
                 {
                     return  nums[i];
                 }
             }
         }
         return  0;
     }
};

思路2:

采用双循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int  majorityElement(vector< int >& nums) {
     int  hit = 0;
     int  currentElem;
     for  ( int  i = 0; i < nums.size(); i++)
     {
         currentElem = nums[i];
         hit = 0;
         for  ( int  j = 0; j < nums.size(); j++)
         {
             if  (nums[j] == currentElem)
             {
                 hit++;
                 if  (hit > nums.size() / 2)
                 {
                     return  currentElem;
                 }
             }
         }
     }
     return  0;
}




本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836477

目录
打赏
0
1
1
1
344
分享
相关文章
|
5月前
|
Leetcode 初级算法 --- 数组篇
Leetcode 初级算法 --- 数组篇
66 0
LeetCode第53题最大子数组和
LeetCode第53题"最大子数组和"的解题方法,利用动态规划思想,通过一次遍历数组,维护到当前元素为止的最大子数组和,有效避免了复杂度更高的暴力解法。
LeetCode第53题最大子数组和
LeetCode------找到所有数组中消失的数字(6)【数组】
这篇文章介绍了LeetCode上的"找到所有数组中消失的数字"问题,提供了一种解法,通过两次遍历来找出所有未在数组中出现的数字:第一次遍历将数组中的每个数字对应位置的值增加数组长度,第二次遍历找出所有未被增加的数字,即缺失的数字。
|
5月前
【LeetCode-每日一题】 删除排序数组中的重复项
【LeetCode-每日一题】 删除排序数组中的重复项
42 4
|
5月前
|
Leetcode第三十三题(搜索旋转排序数组)
这篇文章介绍了解决LeetCode第33题“搜索旋转排序数组”的方法,该问题要求在旋转过的升序数组中找到给定目标值的索引,如果存在则返回索引,否则返回-1,文章提供了一个时间复杂度为O(logn)的二分搜索算法实现。
45 0
Leetcode第三十三题(搜索旋转排序数组)
LeetCode第81题搜索旋转排序数组 II
文章讲解了LeetCode第81题"搜索旋转排序数组 II"的解法,通过二分查找算法并加入去重逻辑来解决在旋转且含有重复元素的数组中搜索特定值的问题。
LeetCode第81题搜索旋转排序数组 II
|
5月前
|
Leetcode第53题(最大子数组和)
这篇文章介绍了LeetCode第53题“最大子数组和”的动态规划解法,提供了详细的状态转移方程和C++代码实现,并讨论了其他算法如贪心、分治、改进动态规划和分块累计法。
101 0
|
5月前
|
C++
【LeetCode 12】349.两个数组的交集
【LeetCode 12】349.两个数组的交集
37 0
LeetCode第34题在排序数组中查找元素的第一个和最后一个位置
这篇文章介绍了LeetCode第34题"在排序数组中查找元素的第一个和最后一个位置"的解题方法,通过使用双指针法从数组两端向中间同时查找目标值,有效地找到了目标值的首次和最后一次出现的索引位置。
LeetCode第34题在排序数组中查找元素的第一个和最后一个位置
LeetCode第33题搜索旋转排序数组
这篇文章介绍了LeetCode第33题"搜索旋转排序数组"的解题方法,通过使用二分查找法并根据数组的有序性质调整搜索范围,实现了时间复杂度为O(log n)的高效搜索算法。
LeetCode第33题搜索旋转排序数组
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等