这周刚开始讲了一点Divide-and-Conquer的算法,于是这周的作业就选择在LeetCode上找分治法相关的题目来做。

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.

这道题是难度为Easy的题目。看到这个题目我首先想到的(除去暴力算法)就是通过排序将相同的元素放在一起。由于这个题目的主元素出现次数一定大于n/2次,所以我想到的办法是排序后取最中间的元素(这个元素一定是主元素)。

想到这一点,程序就相当简单。复杂度为O(nlogn)。

//排序取中间数
#include<vector>
#include<algorithm>
using namespace std; class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums.at(nums.size() / 2);
}
};

当然,这周学的是分治法。我用上面的方法通过了这道题之后再尝试着用分治法的思路去做这道题。长时间思考后无果,看了LeetCode里面的Solution,解法如下。注释是我自己加的。

//Didive-and-Conquer Solution
class Solution {
public:
int majorityElement(vector<int>& nums) {
return majority(nums, 0, nums.size() - 1);
}
private:
// left为最左端元素,right为最右端元素,mid为中间元素
// 返回条件为最左端元素等于最右端元素
// 将问题分为两半递归下去
//
int majority(vector<int>& nums, int left, int right) {
if (left == right) return nums[left];
int mid = left + ((right - left) >> 1);
int lm = majority(nums, left, mid);
int rm = majority(nums, mid + 1, right);
if (lm == rm) return lm;
// 关键 —— 合并结果
return count(nums.begin() + left, nums.begin() + right + 1, lm) > count(nums.begin() + left, nums.begin() + right + 1, rm) ? lm : rm;
}
};

那除了分治法以外,我还看到了一些十分有意思的解法——

一个是随机算法,随机生成一个index,然后遍历这个数组,统计这个index下的元素在数组里的出现次数,如果超过n/2就确认是主元素。这是一个不稳定的O(n)的算法。

class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
srand(unsigned(time(NULL)));
while (true) {
int idx = rand() % n;
int candidate = nums[idx];
int counts = 0;
for (int i = 0; i < n; i++)
if (nums[i] == candidate)
counts++;
if (counts > n / 2) return candidate;
}
}
};

我看到的另一个有趣的解法是用栈的方法来遍历数组:当栈为空时,压入一个元素;当栈不为空时,当前元素跟栈内元素进行比较,如果相同则压入栈内,如果不同则将栈内元素弹出(当前元素不压栈)。当遍历完整个数组后,栈内剩下的元素一定会是主元素。

public class Solution {
public int majorityElement(int[] num) { int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--; }
return major;
}
}

Week1 - 169.Majority Element的更多相关文章

  1. 169. Majority Element(C++)

    169. Majority Element Given an array of size n, find the majority element. The majority element is t ...

  2. 23. leetcode 169. Majority Element

    169. Majority Element Given an array of size n, find the majority element. The majority element is t ...

  3. LeetCode Javascript实现 169. Majority Element 217. Contains Duplicate(两个对象比较是否相等时,如果都指向同一个对象,a==b才是true)350. Intersection of Two Arrays II

    169. Majority Element /** * @param {number[]} nums * @return {number} */ var majorityElement = funct ...

  4. leetcode 169. Majority Element 、229. Majority Element II

    169. Majority Element 求超过数组个数一半的数 可以使用hash解决,时间复杂度为O(n),但空间复杂度也为O(n) class Solution { public: int ma ...

  5. Leetcode#169. Majority Element(求众数)

    题目描述 给定一个大小为 n 的数组,找到其中的众数.众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素. 你可以假设数组是非空的,并且给定的数组总是存在众数. 示例 1: 输入: [3,2,3] ...

  6. 169. Majority Element - LeetCode

    Question 169. Majority Element Solution 思路:构造一个map存储每个数字出现的次数,然后遍历map返回出现次数大于数组一半的数字. 还有一种思路是:对这个数组排 ...

  7. ✡ leetcode 169. Majority Element 求出现次数最多的数 --------- java

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  8. (Array)169. Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  9. LeetCode 169. Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appear ...

随机推荐

  1. 说说无线路由器后门的那些事儿(1)-D-Link篇

    [原创]说说无线路由器后门的那些事儿(1)-D-Link篇 作 者: gamehacker 时 间: 2013-11-29,11:29:19 链 接: http://bbs.pediy.com/sho ...

  2. input check复选框选择后修改<a>标签超链接href

    1. 给复选框添加onclick事件 获取标签id <tbody> <c:forEach var="file" items="${files}" ...

  3. wpf textbox ctrl+enter事件

    <TextBox x:Name="xcontent" Text="sfasdf" Grid.Row="0" AcceptsReturn ...

  4. 第三次作业—Wordcount

    一.地址 Github项目地址:https://github.com/1320068008/WordCount-1 同伴蒋鑫作业地址:https://www.cnblogs.com/JxsBK/p/1 ...

  5. 如何保证Redis与数据库的数据一致性

    一般来说,只要你用到了缓存,不管是Redis还是memcache,就可能会涉及到数据库缓存与数据的一致性问题,这里我们以Redis为例. 我们该如何保证Redis与数据库的一致性呢? So easy: ...

  6. 深入理解MySql事务

    事务是MySQL等关系型数据库区别于NoSQL的重要方面,是保证数据一致性的重要手段.本文将首先介绍MySQL事务相关的基础概念,然后介绍事务的ACID特性,并分析其实现原理. MySQL博大精深,文 ...

  7. java调用存储过程的方式

    1.问号是入参和出参,出参要指定类型 CallableStatement pstmt = conn.prepareCall("{call dbo.UP_CodeUp_***(?,?,?,?, ...

  8. 【leetcode】410. Split Array Largest Sum

    题目如下: Given an array which consists of non-negative integers and an integer m, you can split the arr ...

  9. eclipse设置maven web项目打包

    如图:eclipse下的maven web项目,打包部署到本地tomcat时,需要关注的2个方面: 1. src/main/webapp目录下的文件,打包到/ 根路径下 2. 添加maven 依赖,打 ...

  10. mysql 语句积累

    show tables; 显示表 DROP TABLE IF EXISTS emp;删除表