剑指offer之数组中数字出现一次
来源:互联网 发布:贵阳浪人网络 编辑:程序博客网 时间:2024/05/17 23:24
题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
数组a中只有一个数出现一次,其他数都出现了2次,找出这个数字
public static int find1From2(int[] a){ int len = a.length, res = 0; for(int i = 0; i < len; i++){ res = res ^ a[i]; } return res; }
数组中有两个出现一次的数字,其他数字都出现两次,找出这两个数字
//num1,num2分别为长度为1的数组。传出参数//将num1[0],num2[0]设置为返回结果public class Solution { public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { if(array == null || array.length <= 1){ num1[0] = num2[0] = 0; return; } /** *用位运算实现,如果将所有所有数字相异或,则最后的结果肯定是那两个只出现一次的数字异或的结果sum, 所以根据异或的结果1所在的最低位,把数字分成两半,每一半里都还有只出现一次的数据和成对出现的数据 这样继续对每一半相异或则可以分别求出两个只出现一次的数字 */ int len = array.length, index = 0, sum = 0; for(int i = 0; i < len; i++){ sum ^= array[i]; }//两个出现一次的数异或的结果sum for(index = 0; index < 32; index++){ if((sum & (1 << index)) != 0) break; }//找出1所在的最低位 for(int i = 0; i < len; i++){ if((array[i] & (1 << index))!=0){ num2[0] ^= array[i]; }else{ num1[0] ^= array[i]; } } }}
数组a中只有一个数出现一次,其他数字都出现了3次,找出这个数字
public static int find1From3(int[] a){ int[] bits = new int[32];//32位bit int len = a.length; for(int i = 0; i < len; i++){ for(int j = 0; j < 32; j++){ //bits[j]为每个数位为1的位置 bits[j] = bits[j] + ( (a[i]>>>j) & 1); } } int res = 0; for(int i = 0; i < 32; i++){ //bits[i]不为3则证明该数出现1次 if(bits[i] % 3 !=0){ res = res | (1 << i); } } return res; }
阅读全文
0 0
- 剑指Offer之 - 数组中只出现一次的数字
- 【剑指offer】之数组中只出现一次的数字
- 【剑指offer之数组中只出现一次的数字】
- 剑指offer之数组中数字出现一次
- 【剑指offer】Q40:数组中出现一次的数字
- 剑指offer--数组中只出现一次的数字
- [剑指Offer]40.数组中只出现一次的数字
- 剑指offer-40 数组中只出现一次的数字
- 剑指offer 数组中只出现一次的数字
- 剑指offer 40-数组中只出现一次的数字
- 《剑指offer》数组中只出现一次的数字
- 剑指offer—数组中只出现一次的数字
- [剑指offer-1351]数组中只出现一次的数字
- 剑指offer:数组中只出现一次的数字
- 剑指offer 40 数组中只出现一次的数字
- 剑指offer:数组中只出现一次的数字
- 剑指offer 数组中只出现一次的数字
- [剑指offer]数组中只出现一次的数字
- HDU 5125 Magic Balls DP(LIS变形)
- HDU2665 主席树原理解决静态区间第K大值问题总结 有详细图解和代码解释
- Android自定义View的实现方式(三种)
- RecyclerView的使用及理解
- tensor flow学习网站
- 剑指offer之数组中数字出现一次
- leetcode 365. Water and Jug Problem 两个水杯倒水问题 + Gcd辗转相除法
- ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛 Minimum
- 综合指南: 何时使用 Em 与 Rem
- Redis持久化方法
- iOS成长之路-- XCode工程中 Project 和 Targets区别
- 什么是P问题、NP问题和NPC问题
- [codevs4267]阮神的妹子们
- 奋斗群群赛17总结与心得(未完)