8ms C solution using hash table


  • 0
    int majorityElement(int* nums, int numsSize) {
        int i = 0;
        int idx;
        int hashkey[numsSize];
        int hashvalue[numsSize];
        int halfsize = numsSize/2; 
        int majority;
    
        for(i = 0;i < numsSize;i++){
            hashvalue[i] = 0;
        }
    
        for(i = 0;i < numsSize;i++){
            idx = (nums[i] + numsSize) % numsSize;
        
            if(hashvalue[idx] == 0){
                hashkey[idx] = nums[i];
                hashvalue[idx]++;
            }
            else if(nums[i] == hashkey[idx]){
                hashvalue[idx]++;
            }
            else{
                while(hashvalue[idx] != 0){
                    idx = (idx + 1)% numsSize;
                }
                hashkey[idx] = nums[i];
                hashvalue[idx]++;
            }
        }
    
        for(i = 0; i < numsSize; i++){
            if(hashvalue[i] > halfsize){
                majority = hashkey[i];
                break;
            }
        }
    
        return majority;
    }

  • 0
    C

    [10,-57,-57,-57,2] may challenge?


Log in to reply
 

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