这周刚开始讲了一点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. webstorm 打开后目录结构不完整

    问题: webstorm自动生成的配置文件.idea/modules.xml损坏了,其实是我把这个.idea目录整个删了 解决方法: 1.删除本地目录历史 点击close Project(若是打开多个 ...

  2. http参数传递方式

    url传参 这种在各种method(get,post,delete,put)都能使用,解析速度快 body体中的参数 application/x-www-form-urlencoded 这应该是最常见 ...

  3. 自然语言处理资源NLP

    转自:https://github.com/andrewt3000/DL4NLP Deep Learning for NLP resources State of the art resources ...

  4. [HTTP知识体系]前端常用的一些参数

    1.http常见状态码(status code) 200(成功) 服务器已成功处理了请求.通常,这表示服务器提供了请求的网页. 301 (永久移动) 请求的网页已永久移动到新位置. 服务器返回此响应( ...

  5. 外网无法ping自己的linux服务器

    Linux默认是允许Ping响应的,系统是否允许Ping由2个因素决定的:A.内核参数,B.防火墙,需要2个因素同时允许才能允许Ping,2个因素有任意一个禁Ping就无法Ping. 具体的配置方法如 ...

  6. react 详细解析学习笔记

    React的介绍: React来自于Facebook公司的开源项目 React 可以开发单页面应用       spa(单页面应用) react 组件化模块化  开发模式 React通过对DOM的模拟 ...

  7. SpringToolSuit(STS)添加了Lombok后仍然报错

    参见这篇博客 https://blog.csdn.net/qq_27442469/article/details/90612918 上面步骤做完后,在项目右键->Maven->Update ...

  8. es6的...用法

    ...将一个数组转为用符号分隔的参数序列 1.console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5 2. var args = [0, 1, 2]; f.apply ...

  9. SpringMVC最新教程IDEA版

    1.servlet项目结构与识别 Idea里带个蓝点的文件夹为tomcat吃的网站内容,idea会通过“Web Resource Directory”来标注,会被打成一个war包 这个文件夹里,MET ...

  10. @PathVariable注解使用

    @PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值 语法: @PathVariable("xxx")通过 @PathVariable 可以将URL ...