码迷,mamicode.com
首页 > 其他好文 > 详细

169. Majority Element

时间:2018-03-21 19:50:42      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:void   string   turn   down   uri   esc   i++   blog   public   

原题链接:https://leetcode.com/problems/majority-element/description/
这道题目之前《剑指Offer》见到过,这次就直接能想起书上写的第二种较为简单的方法了:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.majorityElement(new int[]{1, 2, 2, 3, 2, 5}));
        System.out.println(s.majorityElement(new int[]{1, 2, 2, 3, 2, 5, 8, 8, 8, 7, 6, 5, 8}));
    }

    public int majorityElement(int[] nums) {
        int times = 1;
        int temp = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == temp) {
                times++;
            } else {
                if (times > 0) {
                    times--;
                } else {
                    temp = nums[i];
                    times = 1;
                }
            }
        }

        return temp;
    }
}

第一种方法,就是利用快速排序的思想来解决啦!

参考

http://www.cnblogs.com/optor/p/8568645.html

169. Majority Element

标签:void   string   turn   down   uri   esc   i++   blog   public   

原文地址:https://www.cnblogs.com/optor/p/8618905.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!