zoukankan      html  css  js  c++  java
  • 一个数组中有偶数个数相同,需要找出不同的那个数,要求复杂度为O(n)

    先介绍java中的一种运算,叫 “异或”,符号为 ‘ ^ ’ ,其主要是对两个操作数进行位的异或运算(操作时候自动转换成二进制数),位相同的取0,相反取1。若两操作数相同时,互相抵消。

    例:
    1010(10),1110(14),1010(10)

    操作 :1010 ^ 1110 = 0100

        0100 ^ 1010 = 1110 => 14

      找出不同的数 14 (看作是一种相互抵消)

    见问题:

      一个数组中有偶数个数相同(或者是两两成对,有且仅有一个是单独的数),需要找出不同的那个数,要求复杂度为O(n)

      (如果复杂度不为n的话,解决的方式就有很多了)

    见代码:

    public class Solution {
        public static int singleNumber(int[] arr) {
            int result = 0;
            int len=arr.length;
            for (int i = 0; i < len; i++)
            {
                result = result ^ arr[i];
            }
            return result;
        }
    
        public static void main(String[] args) {
            int[] nums ={9,8,7,6,9,4,55,55,8,7,6};
            int key= singleNumber(nums);
            System.out.println("不同的数为:"+key);
        }
    }

    结果为:

  • 相关阅读:
    构建乘积数组
    数组中重复的数字
    把字符串转换成整数
    不用加减乘除做加法
    求1+2+3+...+n
    孩子们的游戏(圆圈中最后剩下的数)
    翻转单词顺序列
    扑克牌顺子
    左旋转字符串
    ES6必知必会 —— Module
  • 原文地址:https://www.cnblogs.com/Mark-blog/p/12896906.html
Copyright © 2011-2022 走看看