zoukankan      html  css  js  c++  java
  • Leetcode题目136.只出现一次的数字(简单)

    ---恢复内容开始---

    题目描述:

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

    说明:

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

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

    思路分析:

    思路一:暴力枚举

    思路二:Hash,空间换时间

    思路三:异或(两个数异或,相同为0,相异为1,1表示真,0表示假)

    代码实现:

    解法一:暴力枚举

    class Solution {
       public static int singleNumber(int[] nums) {
    
            int cur;
            for (int i = 0; i < nums.length; i++) {
                cur = nums[i];
                boolean flag = false;
                for (int j = 0; j < nums.length; j++) {
                    if (nums[j] == cur&&i!=j) {
                        flag = true;
                    }
                }
                if (!flag) {
                    return cur;
                }
            }
            //没有找到这样的元素
            return -1;
        }
    }

    时间复杂度:O(n^2)

    空间复杂度:O(1)

    解法二:

    class Solution {
          public static int singleNumber(int[] nums) {
    
            //用空间换时间:key代表元素值,value代表出现的次数
            Map<Integer, Integer> map = new HashMap<>(nums.length);
            for (int i = 0; i < nums.length; i++) {
                Integer count = map.get(nums[i]);
                map.put(nums[i], count == null ? 1 : ++count);
            }
            for (Integer num : map.keySet()) {
                if (map.get(num) == 1) {
                    return num;
                }
            }
            return -1;
        }
    }

    时间复杂度:O(N)

    空间复杂度:O(N)

    解法三:异或

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

    时间复杂度:O(N)

    空间复杂度:O(1)

  • 相关阅读:
    Go笔记-接口(interface)
    Go学习笔记-结构体中的方法
    Go学习笔记-数组和切片
    处理器的工作流程
    MySQL重温笔记-索引
    Mysql中为什么应该尽量避免使列默认值为NULL
    which、whereis、find的区别
    linux下查找大文件和大目录
    【转】Linux设置定时任务方法
    [转]python中np.multiply()、np.dot()和星号(*)三种乘法运算的区别
  • 原文地址:https://www.cnblogs.com/ysw-go/p/11849272.html
Copyright © 2011-2022 走看看