zoukankan      html  css  js  c++  java
  • LeetCode 169. 多数元素

    我的LeetCode:https://leetcode-cn.com/u/ituring/

    我的LeetCode刷题源码[GitHub]:https://github.com/izhoujie/Algorithmcii

    LeetCode 169. 多数元素

    题目

    给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

    你可以假设数组是非空的,并且给定的数组总是存在多数元素。

    示例 1:

    输入: [3,2,3]
    输出: 3
    

    示例 2:

    输入: [2,2,1,1,1,2,2]
    输出: 2
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/majority-element
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题思路

    思路1-HashMap统计

    HashMap统计,且同时检测当前值是否是多数;

    算法复杂度:

    • 时间复杂度: $ {color{Magenta}{Omicronleft(n ight)}} $
    • 空间复杂度: $ {color{Magenta}{Omicronleft(n ight)}} $

    思路2-对冲

    把大于一半的那个数作为一部分,把其他数作为另一部分,这两部分对冲以后必定只剩大于一半的那个数;

    算法复杂度:

    • 时间复杂度: $ {color{Magenta}{Omicronleft(n ight)}} $
    • 空间复杂度: $ {color{Magenta}{Omicronleft(1 ight)}} $

    算法源码示例

    package leetcode;
    
    import java.util.HashMap;
    
    /**
     * @author ZhouJie
     * @date 2020年5月3日 下午11:54:31 
     * @Description: 面试题39. 数组中出现次数超过一半的数字
     *
     */
    public class LeetCode_Offer_39 {
    
    }
    
    class Solution_Offer_39 {
    	/**
    	 * @author: ZhouJie
    	 * @date: 2020年5月3日 下午11:55:17 
    	 * @param: @param nums
    	 * @param: @return
    	 * @return: int
    	 * @Description: 1-使用HashMap统计;
    	 *
    	 */
    	public int majorityElement_1(int[] nums) {
    		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    		int half = nums.length >> 1;
    		for (int val : nums) {
    			map.put(val, map.getOrDefault(val, 0) + 1);
    			if (map.get(val) > half) {
    				return val;
    			}
    		}
    		return nums[0];
    	}
    
    	/**
    	 * @author: ZhouJie
    	 * @date: 2020年5月4日 上午12:03:11 
    	 * @param: @param nums
    	 * @param: @return
    	 * @return: int
    	 * @Description: 2-直接统计:把数组看为两部分,一部分是目标数,一部分是非目标数,因为目标数过半,所以对冲后最终会剩下目标数;
    	 *
    	 */
    	public int majorityElement_2(int[] nums) {
    		int count = 0, target = nums[0];
    		for (int i = 0; i < nums.length; i++) {
    			if (target == nums[i]) {
    				count++;
    			} else {
    				count--;
    				if (count == 0) {
    					target = nums[i + 1];
    				}
    			}
    		}
    		return target;
    	}
    
    }
    
    
  • 相关阅读:
    针式电子书下载列表(暂时)
    硬盘坏道造成SQL 2000的异常
    一种“您无权查看该网页”的原因和解决方法
    学习英语的一些方法
    “针式背单词”帮助文件
    ClickOnce的Excel模板文件发布
    IC 设计书籍和相关资料
    Useful links on GPU Programming &Examp; Architecture
    点评美国名校的(EE)和(CS)
    微电子/物理学名人 约翰·巴丁 John Bardeen
  • 原文地址:https://www.cnblogs.com/izhoujie/p/12876398.html
Copyright © 2011-2022 走看看