229. 求众数 II 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素. 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1). 示例 1: 输入: [3,2,3] 输出: [3] 示例 2: 输入: [1,1,1,3,3,2,2,2] 输出: [1,2] class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> res = new Ar…
求众数II 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素. 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1). 示例 1: 输入: [3,2,3] 输出: [3] 示例 2: 输入: [1,1,1,3,3,2,2,2] 输出: [1,2] 摩尔投票法的基本思想很简单,在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除.这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半.如果只存在一种元素,那么这…
题目描述 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素. 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1). 示例 1: 输入: [3,2,3] 输出: [3] 示例 2: 输入: [1,1,1,3,3,2,2,2] 输出: [1,2] 解题思路 由于数组中出现次数超过 $\frac{1}{3}$ 的数字最多只可能为两个,所以记录两个数字n1.n2,以及他们出现的次数c1.c2,遍历数组并做以下操作: 若当前两数字出现则把对应的次数加1: 若其中一个…
Q: 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素. 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1). 示例 1: 输入: [3,2,3] 输出: [3] 示例 2: 输入: [1,1,1,3,3,2,2,2] 输出: [1,2] A: 一个叫摩尔投票的算法,可以在一次遍历中找出一个数组中的众数(出现次数一半以上的).通过设置一个计数器和当前'众数',若再遇到当前众数计数器加1,遇到其他数字减一,计数器归零时更新当前众数.巧妙之处是每次归零时前面划…
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. 解题思路: <编程之美>寻找发帖水王的原题,两次遍历,一次遍历查找可能出现次数超过nums.length/3的数字,(出现三次不同的数即抛弃),第二次验证即可. JAVA实现如下: public Lis…
public static int majorityElement(int[] nums) { int num = nums[0], count = 1; for(int i=1;i<nums.length;i++){ if(nums[i] == num) { count++; } else if(--count < 0) { num = nums[i]; count = 1; } } return num; }…
1 leetcode50 计算 x 的 n 次幂函数. 实现 pow(x, n) ,即计算 x 的 n 次幂函数. (1)调用库函数 (2)暴力o(N) (3)分治 xxxxxx.......x   采用两端夹,如果是偶数 y=x的二分之n次方  result=y*y.如果是奇数,x的二分之n次方,result=y*y*x x(n)->x(n/2)->x(n/4).....x(0)  每次减半,logn class Solution(object): def myPow(self, x, n)…
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same le…
There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a l…
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]] 解题思路: 参考Java for LeetCode 054 Spiral Matrix,修改下…