Monday, November 23, 2015

[leetcode] Majority Element II

难就难在怎么说服自己去相信投票方法有效
 --办法 把公式写出来 自己想一想
if statement order不要得意忘形,要分门别类写好
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> result = new ArrayList<Integer>();
        if (nums == null || nums.length == 0) return result;
        if (nums.length == 1){
            result.add(nums[0]);
            return result;
        }
        int v1 = 0;
        int v2 = 0;
        int c1 = 0;
        int c2 = 0;
        for (int i = 0; i < nums.length; i++){
            if (c1 != 0 && c2 != 0 && v1 != nums[i] && v2 != nums[i]){
                c1--;
                c2--;
            }else if (c1 != 0 && v1 == nums[i]){
                c1++;
            }else if (c2 != 0 && v2 == nums[i]){
                c2++;
            }else if (c1 == 0){
                c1++;
                v1 = nums[i];
            }else if (c2 == 0){
                c2++;
                v2 = nums[i];
            }
            
        }
        if (c1 != 0){
            c1 = 0;
            for (int i = 0; i < nums.length; i++){
                if (nums[i] == v1) c1++;
            }
            if (c1 > nums.length/3) result.add(v1);
        }
        if (c2 != 0){
            c2 = 0;
            for (int i = 0; i < nums.length; i++){
                if (nums[i] == v2) c2++;
            }
            if (c2 > nums.length/3) result.add(v2); 
        }
        return result;
    }
}

No comments:

Post a Comment