题目 主元素II 给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一. 样例 给出数组[1,2,1,2,1,3,3] 返回 1 注意 数组中只有唯一的主元素 挑战 要求时间复杂度为O(n),空间复杂度为O(1). 解题 利用HashMap,key值是元素值,value是出现次数,但是时间复杂度和空间复杂度都是O(N) public class Solution { /** * @param nums: A list of integers * @return: Th…
题目 主元素 III 给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k. 样例 ,返回 3 注意 数组中只有唯一的主元素 挑战 要求时间复杂度为O(n),空间复杂度为O(k) 解题 上一题刚介绍过所用的方法,但是这个确实很复杂的 先利用HashMap实现 public class Solution { /** * @param nums: A list of integers * @param k: As described * @return: The major…
题目 搜索旋转排序数组 II 跟进“搜索旋转排序数组”,假如有重复元素又将如何? 是否会影响运行时间复杂度? 如何影响? 为何会影响? 写出一个函数判断给定的目标值是否出现在数组中. 样例 给出[3,4,4,5,7,0,1,2]和target=4,返回 true 解题 直接法 class Solution: """ @param A : an integer ratated sorted array and duplicates are allowed @param targ…
主元素 II 给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一. 样例 给出数组[1,2,1,2,1,3,3] 返回 1 注意 数组中只有唯一的主元素 挑战 要求时间复杂度为O(n),空间复杂度为O(1). 嗯.. 百度了一下. 主元素可能有两个,于是设置两个当前主元素.遍历nums,如果和某个当前住元素相等,则计数加一.如果都不相等 计数减一,若减后计数小于等于0,则将对应的当前住元素更换. 最后需要验证,应为当前主元素只有一个,候选有两个. lintcode上…
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. 求主元素:包括n个元素的数组中.假设一个元素的出现次数大…
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. 求主元素,这次的是大于sz/3就算是主元素,可以分为两轮查找,第一轮先查找元素数目较多的两个元素(可能不属于主元素),第二次再遍历来查找上面两个元素是否符合条件,代码如下: class Solution…
题目: Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it. Notice You may assume that the array is non-empty and the majority number always exist in the array. Have you met this que…
题目 落单的数 II 给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字. 样例 给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4 挑战 一次遍历,常数级的额外空间复杂度 解题 可以利用HashMap直接解决,时间复杂度和空间复杂度都是O(N) 1.map中存在该元素则:map.put(num,map.get(num) + 1) 2.map中不存在该元素则:map.put(num , 1) 3.map中这个元素出现次数等于三次,则删除该元素 空间复杂…
题目 带重复元素的子集 给定一个可能具有重复数字的列表,返回其所有可能的子集 样例 如果 S = [1,2,2],一个可能的答案为: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] 注意 子集中的每个元素都是非降序的 两个子集间的顺序是无关紧要的 解集中不能包含重复子集 挑战 你可以同时用递归与非递归的方式解决么? 解题 一个很简单的想法就是在上一题目中增加判断是否已经存在某个子集 class Solution: """ @param S: A…
题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递归的时候才能保存结果,参考程序 java程序: class Solution { /** * Calculate the total number of distinct N-Queen solutions. * @param n: The number of queens. * @return:…