LeetCode 137. Number II that only appears once (java implementation)

137. Number II that appears only once

You are given an integer array nums. Except for an element that appears only once, each element appears exactly three times. Please find and return the element that appears only once.

Example 1:

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

Example 2:

输入:nums = [0,1,0,1,0,1,99]
输出:99

hint:

  • 1 <= nums.length <= 3 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • In nums, except for an element that appears only once, every other element appears exactly three times.

Answer ideas:

  • This method can be used as a brute force solution to find duplicate elements in an array.
  • Starting from the first element and comparing with each subsequent element, if the same value appears, count count++
  • When the second element is compared sequentially, the count is set to 0 and the count is restarted.
  • If in that cycle, the count is 1, it means that the value only appears once, record the value, break to exit all loops, and return the number.
class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        // 从第一个元素开始和后面的每一个元素比较,若有相同的数值出现,则计数count++,当第二个元素依次往后比的时候,计数count置0,重新计数,如果在那轮循环中,计数为1说明该数值只出现了一次,记录该数值,将其返回即可
        int key=0;
    for (int i = 0; i < nums.length; i++) {
    
    
            int count=0;//无脑遍历计数,外层遍历相当于哨兵
            for (int j = 0; j < nums.length; j++) {
    
    
                if(nums[i]==nums[j]){
    
    //内层循环相当于比对计数
                    count++;        //当前数字每出现就计数
                }
            }
            if(count==1){
    
    
               key =nums[i];        //记录那个只出现一次的数值,并将其返回
            }
        }
        return key;
    }
}

Guess you like

Origin blog.csdn.net/qq_44243059/article/details/125899138