zoukankan      html  css  js  c++  java
  • leetcode-只出现一次的数字

    题目:只出现一次的数字

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

    说明:

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

    示例 1:

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

    示例 2:

    输入: [4,1,2,1,2]
    输出: 4
    • 第一种

    使用Hash创建key-value映射

    代码:

        public int singleNumber(int[] nums) {
            Map<Integer, Integer> map = new HashMap();
            for (int num : nums) {
                map.put(num, map.containsKey(num) ? 0 : 1);
            }
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                if (entry.getValue() == 1) {
                    return entry.getKey();
                }
            }
            return -1;
        }
    • 第二种

    在解题时应该充分考虑题目所给的条件。

    比如“给定一个整数数组,除了某个元素外其余元素均出现两次”,我们由此可以知道,若该数组有序,且有一个元素只出现一次,以步数2向后遍历,那么一定会存在a[i] != a[i+1]

    代码:

        public int singleNumber2(int[] nums) {
            Arrays.sort(nums);
    
            for (int i = 0; i < nums.length ; i = i + 2) {
                if (i + 1 >= nums.length ) {
                    return nums[i];
                }
                if (nums[i] != nums[i + 1]) {
                    return nums[i];
                }
            }
    
            return -1;
        }
    • 第三种

    使用异或:数a两次异或同一个数b(a=a^b^b)仍然为原值a.

    异或口诀: 相同取0,相异取1

    0^4
    0000 0000
    0000 0100
    =
    0000 0100

    4^2=6 0000 0100 ^ 0000 0010 = 0000 0110 6^2=4 0000 0110 ^ 0000 0010 = 0000 0100

    代码:

        public int singleNumber3(int[] nums) {
            Arrays.sort(nums);
            int res = 0;
            for (int num : nums) {
                res ^= num;
            }
            return res;
    
        }

    参考:https://blog.csdn.net/biezhihua/article/details/79571917

    代码:https://gitee.com/hapzxb/LeetCode/blob/master/leetcode/src/main/java/com/hapzxb/leetcode/array/SingleNumber.java

  • 相关阅读:
    线程3 线程池和文件下载服务器
    线程 2
    线程 1
    线程间操作
    编写高质量的代码-------从命名开始
    基于.NET平台常用的框架整理
    消息队列
    我是一个线程
    linux 网络命令
    css hack比较全 --- 转
  • 原文地址:https://www.cnblogs.com/kingxiaozi/p/10544914.html
Copyright © 2011-2022 走看看