卷心菜修炼日记 - 只出现一次的数字

162 阅读2分钟

点赞再看,养成习惯


题目

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素

链接leetcode.cn/problems/si…

说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

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

示例 2:

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

思路

1. 暴力破解

第一种思路很简单,我们只需要遍历数组,将每一个元素进行比对即可。

代码实现

class Solution {
    public int singleNumber(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            boolean flag = true;
            for (int j = 0; j < arr.length; j++) {
                if (i == j) {
                    continue;
                }
            if (arr[i] == arr[j]){
                flag = false ;
            }
            }
            if (flag){
                return arr[i];
            }
        }
        return -1 ;
    }
}

时间复杂度: O(n) = n²


2. 排序后进行比对

我们也可以先进行一次排序,然后再进行比对

class Solution {
    public int singleNumber(int[] nums) {
  //快速排序
        Arrays.sort(nums);
        if (nums.length == 1) {
            return nums[0];
        }
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                if (nums[i] != nums[i + 1]) {
                    return nums[i];
                } else {
                    continue;
                }
            }
            if (i == nums.length - 1) {
                if (nums[i] != nums[i - 1]) {
                    return nums[i];
                } else {
                    break;
                }
            }
            if (nums[i] == nums[i + 1] || nums[i] == nums[i - 1]) {
                continue;
            } else {
                return nums[i];
            }
        }
        return -1;
        
        
        
        
        
    }
}

3. 位运算

前两种方式很多同学很简单的就可以想出来,而对于位运算来说基础一般的同学不太能想得到。在做位运算之前我们首先要了解位运算中异或运算(^)的特性:

a ^ 0 = a
a ^ a = 0 
a ^ a ^ b = b

根据这个特性可得:

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            result ^= nums[i];
        }

        return result ;
    }
}

时间复杂度: O(n) = n

运行结果:

image.png

结语

今天的内容就到此结束了,有疑问的小伙伴欢迎评论区留言或者私信博主,博主会在第一时间为你解答。

码字不易,感到有收获的小伙伴记得要关注博主一键三连,不要当白嫖怪哦~

如果大家有什么意见和建议请评论区留言或私聊博主,博主会第一时间反馈的哦