Problem description ~ a number that appears only once

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

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

Example 1:

 输入: [2,2,1]
输出: 1

Example 2:

 输入: [4,1,2,1,2]
输出: 4
Leetcode original title address: https://leetcode.cn/problems/single-number

solution

Scheme 1 uses map to count the number of occurrences of each item, and sees who has the number of occurrences.

 var singleNumber = function (nums) {
    let map = new Map() // 1. 创建一个map用来统计数据
    for (let i = 0; i < nums.length; i++) { // 2. 遍历数组开始统计
        // 3. 一开始map集合是空的,所以继续往下看
        if (map.has(nums[i])) { // 5. 后续来了一项,新来的这一项原集合中有一样的项
            let conut = map.get(nums[i]) // 6. 就看看原集合中这一项出现了几次
            conut = conut + 1 // 7. 把原有次数新增一次
            map.set(nums[i], conut) // 8. 然后更新次数
        } else { // 4. 来一项,就把这一项存进map里面,key是这一项,value是这一项出现的次数
            map.set(nums[i], 1)
        }
    }
    // 9. 经过这么一波操作,map集合中就记录了,各个项出现的次数了
    for (const [key, value] of map) { // 10. 使用forof遍历集合
        if (value === 1) { // 11. 看看谁出现的次数是一次
            return key // 12. 就把对应项返回出去告知即可
        }
    }
};

Of course, you can also use objects to count the number of times, a reason, which will not be repeated here.

Option 2 If an item appears only once, the indexof and lastIndexOf values are equal

  • If a number appears only once, then the values of indexof and lastIndexOf must be equal
  • If a number appears twice, the values of indexof and lastIndexOf must not be equal
 var singleNumber = function (nums) {
    for (let i = 0; i < nums.length; i++) {
        let item = nums[i]
        if (nums.indexOf(item) === nums.lastIndexOf(item)) {
            return item
        }
    }
};

Note: The difference between indexof and lastIndexOf:

  • The index of the first occurrence of an element in the indexof query (from left to right)
  • lastIndexOf the position of the last occurrence of an element (the difference is from right to left)
  • The indexes returned by both are indexes from left to right

Option 3 uses XOR operation (official recommendation)

This XOR operation is really not thought of. The XOR rule is briefly as follows:

  • XOR 0 of any numeric value is equal to the numeric value itself
  • XOR of two numbers, the same is 0, the difference is 1

So the code is as follows:

 var singleNumber = function (nums) {
    let val = 0; // 1. 定义初始值为0
    nums.forEach((item) => {
        val = val ^ item // 2. 循环异或
    })
    return val // 3. 最终的值就是结果
};

Problem Description ~ Majority Elements

This question of most elements can also be achieved by using the idea of counting the number of times.

Given an array nums of size n, return the majority of its elements. A majority element is an element that occurs more than ⌊ n/2 ⌋ in the array.

You can assume that the array is non-empty and that a given array always has a majority of elements.

Example 1:

 输入:nums = [3,2,3]
输出:3

Example 2:

 输入:nums = [2,2,1,1,1,2,2]
输出:2
Leetcode original title address: https://leetcode.cn/problems/majority-element

solution

Option 1, use map to count the number of times and compare whether it is greater than half of the length of the array

 var majorityElement = function (nums) {
    let map = new Map()
    for (let i = 0; i < nums.length; i++) {
        if (map.has(nums[i])) {
            let conut = map.get(nums[i])
            conut = conut + 1
            map.set(nums[i], conut)
        } else {
            map.set(nums[i], 1)
        }
    }
    for (const [key, value] of map) {
        if (value > nums.length / 2) {
            return key
        }
    }
};

Option 2, median determination

Find the rule:

If there is a number that appears more frequently than n/2, that is to say, this number appears many times, for example, there are five ice creams, and three are small puddings.

Then it is to find the middle number of the ice cream, and then you can find the number that occurs more than n/2. So sort first, and then take the middle number.

 var majorityElement = function (nums) {
    nums.sort(function (a, b) { // 1. 排个序
        return a - b
    })
    let middle = Math.floor(nums.length / 2) // 2. 取到中间数
    return nums[middle] // 3. 返回就是
}

Summarize

The problem is not difficult, there are many methods, but we still have to reserve a guaranteed method, which is to use the map set for statistics.

After all, during the interview, you may be nervous, and you may not be able to think of other ways.


水冗水孚
1.1k 声望585 粉丝

每一个不曾起舞的日子,都是对生命的辜负