[35] Numbers that appear only once | Majority elements (LC 136 | 169)

Starting from today to use java to brush the questions.

A number that appears only once

Problem Description

Given an array of non-empty integers, each element appears twice except for one element. Find the element that appears only once.

Description:

Your algorithm should have linear time complexity. Can you do it without using extra space?

answer

hash table

Additional knowledge points:

The Map collection is based on key/value mapping . Each key can only map one value at most. The key can be the value of any reference data type and cannot be repeated; the value can be the value of any reference data type and can be repeated; the key-value pairs are stored out of order.

Common methods of HashMap :
put(K key, V value): store the key (key)/value (value) mapping in the Map collection.
get(Object key): Returns the value mapped by the specified key, and returns null if there is no value corresponding to the key.
size(): Returns the number of data in the Map collection.
clear(): Clear the Map collection.
isEmpty (): Judge whether there is data in the Map collection, if not, return true, otherwise return false.
remove(Object key): Delete the data whose key is the key in the Map collection and return its corresponding value.
values(): Returns data in the Collection data type format composed of all values ​​in the Map collection.
keySet(): Returns the Set collection composed of all the keys in the Map collection.
containsKey(Object key): Judge whether the specified key is included in the collection, return true if it contains, otherwise return false.
containsValue(Object value): Judge whether the specified value is included in the collection, return true if it contains, otherwise return false.
entrySet(): Convert each key-value of the Map collection into an Entry object and return a Set collection composed of all Entry objects.

4 ways to traverse Map in Java

Algorithm idea 1:

Traverse the array, while counting the number of occurrences of the data, while storing the data as a key and the number of occurrences as a value in the hash table; traversing the hash table, the return value is the key corresponding to 1.

Code 1:

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        Map<Integer, Integer> map = new HashMap<>();
        for(Integer num :nums){
    
    //foreach语句:num == nums[i]
            Integer count = map.get(num);//在map中查找num
            count = count == null ? 1 : ++count;//若count为null,即没找到则令count=1,否则count的值加1
            map.put(num,count);
        }
        for(Integer num : map.keySet()){
    
    //遍历map
            if(map.get(num) == 1)
                return num;
        }
        return 0;
    }
}

Algorithm idea 2:

Traverse the array and store the array elements as keys in the map. Before each storage, check whether there is the same value in the map. If there is, remove it; if not, store it. In the end, the only elements left in the map are what you want.

Code 2:

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        Map<Integer, Integer> map = new HashMap<>();
        for(Integer num :nums){
    
    //foreach语句:num == nums[i]
            Integer count = map.get(num);//在map中查找num
            if(count != null)
                map.remove(num);
            else
                map.put(num,1);
        }
        for(Integer num : map.keySet())//因为map是无序的,所以只能遍历取值
            return num;
        return 0;
    }
}

Time complexity: O(n)
Space complexity: O(n)

Bit operation

Additional knowledge points:

The nature of the exclusive OR operation:

  1. a ⊕ 0 = a ;
  2. a ⊕ a = 0 ;
  3. The exclusive OR operation satisfies the commutative and associative laws.

Algorithm idea: XOR all the elements in the array, because the number that appears twice or the result is 0, 0 and 0 or the result is still 0, the last 0 and the number that only appeared once or come out is that number.

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        int res = 0;
        for (int num : nums) {
    
    
            res ^= num;
        }
        return res;
    }
}

Time complexity: O(n)
Space complexity: O(1)

Majority element

Problem Description

Given an array of size n, find most of the elements in it. Most elements refer to elements that appear more than ⌊ n/2 ⌋ in the array.

You can assume that the array is non-empty, and there will always be a majority of elements in a given array.

answer

hash table

Algorithm idea:

Use the hash table to count the number of occurrences of each element, and return the elements with the number of occurrences greater than ⌊ n/2 ⌋.

Code:

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        Map<Integer,Integer> map = new HashMap<>();
        for(Integer num:nums){
    
    //计数
            Integer count = map.get(num);
            count = count == null ? 1 : ++count;
            map.put(num,count);
        }
        for(Integer num:map.keySet()){
    
    //返回
            Integer n = nums.length;
            if(map.get(num) > n/2)
                return num;
        }
        return 0;
    }
}

Time complexity: O(n)
Space complexity: O(n)

Sort

Algorithm idea:

Because the number of most elements is greater than n/2, the n/2th element after sorting the array must be the majority element.

Code:

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        Arrays.sort(nums);
        int n=nums.length;
        return nums[n/2];
    }
}

Time complexity: O (nlogn)
Space complexity: O (1)

Boyer-Moore voting algorithm

The idea of ​​voting algorithm is:

The initial candidate is nums[0], the initial number of votes is 1, traverse the array, if the same number is encountered, the candidate's votes will be +1, and if a different number is encountered, the candidate's votes will be -1. When the candidate's votes are 0, the candidate will be replaced. People and initialize the number of votes. After traversing the array, the current candidate is the final answer.

principle:

Because the number of most elements is greater than n/2, when it is cancelled with other numbers, its number of votes must be greater than 1, so it will survive to the end.

Code:

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
       int res = nums[0];//res表示候选人
       int tikets = 1;
       for(int num : nums){
    
    
           if(num == res)
            tikets++;
            else tikets --;
            if(tikets == 0){
    
    
                res = num;
                tikets = 1;
            }
       }
       return res;
    }
}

Time complexity: O(n)
Space complexity: O(1)

Experience

Recently, I’ve been a bit gobbled up with the questions, so I still have to calm down and chew slowly~

Guess you like

Origin blog.csdn.net/qq_43424037/article/details/113759003