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

    问题描述:给你一个整型数组,数组中有一个数只出现过一次,其他数都出现了两次,求这个只出现了一次的数。

    方法1:求取数组中的最大值 ,创建一个长度为数组中最大的boolean类型的数组,数组开始存储的为true,遍历整形数组,更改与整数相对应的Boolean数组中的值为反值,遍历完成后,boolean类型数组中为false的下标为改数字

    方法2:二进制

    异或的特点:相同的数异或为0,0和任何数异或还是这个数本身,并且异或支持交换律。  相同为0   不同为1

    所有数异或 获得的就是没有重复的数;

        public static Integer getResult(int[] arr){
            int temp=arr[0];
            for(int i=1;i<arr.length;i++){
                temp=temp^arr[i];
            }
            return temp;
            
        }
    View Code

    如果问题描述改为:给你一个整型数组,数组中有一个数只出现过两次,其他数都出现了一次,求这个出现了两次的数。

    方法1:

        public static Integer getResult(int[] arr){
            Set<Integer> set=new HashSet<>();
            for(int i=0;i<arr.length;i++){
                if(!set.add(arr[i])){
                    return arr[i];
                }
            }
            return null;
            
        }
    View Code
  • 相关阅读:
    webpack简介与使用
    webpack使用小记
    H5常用技巧
    mac 终端 常用命令
    vue.js学习资料
    git clean(转载)
    HTML5 移动端的上下左右滑动问题
    HTML5+CSS3 loading 效果收集--转载
    使用Chrome DevTools的Timeline分析页面性能
    phantomjs 是什么?----主要是mac下面
  • 原文地址:https://www.cnblogs.com/xiatc/p/12372143.html
Copyright © 2011-2022 走看看