bit manipulation method


  • 1
    D

    This method is almost the same as that applied in single number two.

     public class Solution {
        public int majorityElement(int[] nums) {
            if (nums == null || nums.length == 0) return -1;
            int result = 0;
            int[] bits = new int[32];
            
            for (int i = 0; i < 32; i++) {
                for (int j = 0; j < nums.length; j++) {
                    bits[i] += (nums[j] >> i) & 1;
                }
                bits[i] = bits[i] > (nums.length / 2) ? 1 : 0;
                result |= (bits[i] << i);
            }
            
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.