Saturday, January 3, 2015

169: Majority Element

Q:
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.

A:
就是每次dump两个不同的数字。

class Solution:
def majorityElement(self, nums: list[int]) -> int:
# dump two different values at time, whenever a value is different from nums[0] dump both
v0 , v0Count = 0, 0
for num in nums:
if v0Count == 0:
v0 = num
v0Count += 1
elif num == v0:
v0Count += 1
else: # different value, dump both
v0Count -= 1
return v0




用两个地址,记录不同的位置

public class Solution {
    public int majorityElement(int[] nums) {
        int i1= 0;
        for(int i2=0; i2 < nums.length;i2++){
            if(nums[i2] != nums[i1]){
                int val = nums[i1];
                i1++;
                // i1 till not equal
                while(i1<= i2 && nums[i1] != val){
                    i1++;
                }
            }
        }
        return nums[i1];
    }
}


Mistakes:















No comments:

Post a Comment