[Small Y algorithm]⚡Daily LeetCode clock-in⚡- 45. Most elements

Keywords: Java Algorithm leetcode

📢Preface

🚀 Algorithmic problems🚀
  • 🌲 Typing an algorithmic problem every day is both a learning process and a sharing process😜
  • 🌲 Tip: This column uses both C#and Java for problem solving programming languages
  • 🌲 To keep learning every day, let's work together to become the algorithmic God🧐!
  • 🌲 Today is the 45th day of punch-in🎈!
🚀 Algorithmic problems🚀

🌲Sample Theme: Most Elements

Given an array of size n, find most of the elements. Most elements are elements that occur more than n/2_in the array.

You can assume that the array is not empty and that there is always a majority of elements in the given array.

Example 1:

Input:[3,2,3]
Output: 3

Example 2:

Input:[2,2,1,1,1,2,2]
Output: 2

Tips:

  • 2 <= numbers.length <= 3 * 104
  • -1000 <= numbers[i] <= 1000
  • numbers in non-decreasing order
  • -1000 <= target <= 1000
  • There is only one valid answer

🌻C#Method: Voting Method

The majority is always greater than the non-majority, so the number that eventually keeps the count above zero is the majority.

Note: Change candidates whenever count returns to zero and continue counting the number of subsequent votes.

Idea Analysis

Code:

public class Solution {
    public int MajorityElement(int[] nums) {       
       //laws and regulations governing balloting   
        int condidate = nums[0];
        int count = 1;
        for(int j = 1;j<nums.Length;j++)
        {   
            if(count == 0)
            {
                count = 1;
                condidate = nums[j];
                continue;
            }            
            if(nums[j] != condidate)
            {
                count--;
            }   
            else
            {
                count++;
            }                
        }
        return condidate;                  
    }
}

results of enforcement

adopt
 Execution time: 108 ms,At all C# 76.44% of users were defeated in submissions
 Memory consumption: 29.8 MB,At all C# 27.49% of users were defeated in submissions

🌻Java Method 1: Hash Table

Idea Analysis

We know that the elements that occur most often are larger than 2/n times, so we can use a hash table to quickly count the occurrences of each element.

We use hash maps to store each element and the number of occurrences. For each key-value pair in a hash map, a key represents an element and a value represents the number of occurrences of that element.

We iterate through the array nums with a loop and add each element of the array to the hash map.

After that, we iterate through all the key-value pairs in the hash map, returning the key with the largest value.
We can also use the rolling table method when traversing the array nums to maintain the maximum value, thus eliminating the last traversal of the hash map.

Code:

class Solution {
    private Map<Integer, Integer> countNums(int[] nums) {
        Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
        for (int num : nums) {
            if (!counts.containsKey(num)) {
                counts.put(num, 1);
            } else {
                counts.put(num, counts.get(num) + 1);
            }
        }
        return counts;
    }

    public int majorityElement(int[] nums) {
        Map<Integer, Integer> counts = countNums(nums);

        Map.Entry<Integer, Integer> majorityEntry = null;
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {
                majorityEntry = entry;
            }
        }

        return majorityEntry.getKey();
    }
}

results of enforcement

adopt
 Execution time:13 ms,At all Java  21 beats in submission.51%Users
 Memory consumption: 38.6 MB,At all Java 52 defeated in submission.15%Users

Complexity analysis

Time Complexity: O( n )
Spatial Complexity: O( n )

🌻Java Method 2: Randomization

Code:

class Solution {
    private int randRange(Random rand, int min, int max) {
        return rand.nextInt(max - min) + min;
    }

    private int countOccurences(int[] nums, int num) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == num) {
                count++;
            }
        }
        return count;
    }

    public int majorityElement(int[] nums) {
        Random rand = new Random();

        int majorityCount = nums.length / 2;

        while (true) {
            int candidate = nums[randRange(rand, 0, nums.length)];
            if (countOccurences(nums, candidate) > majorityCount) {
                return candidate;
            }
        }
    }
}

results of enforcement

adopt
 Execution time:1 ms,At all Java  99 Defeated in Submission.96%Users
 Memory consumption: 44.5 MB,At all Java 12 beats in submission.18%Users

💬summary

  • Today is the 45th day of punching!
  • This article uses two programming languages C#and Java to solve problems
  • Some methods are also referential, capitalized, and shared as you learn, thank the algorithmic guys again
  • That's the end of today's algorithmic sharing. Bye tomorrow!

🚀Previous quality article sharing

Posted by Hokus on Thu, 30 Sep 2021 09:11:03 -0700