数组中只出现一次的数字(数组)
来源:互联网 发布:linux 文件引用计数 编辑:程序博客网 时间:2024/06/07 11:51
题目描述:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路:
位运算中异或的性质:两个相同数字异或等于0,一个数和0异或还是它本身。
当只有一个数出现一次时,我们把数组中所有的数,依次异或运算,最后剩下的就是落单的数,因为成对儿出现的都抵消了。
只有两个数(假设是A和B)出现一次的数组。首先还是先异或,剩下的数字肯定是A、B异或的结果,这个结果的二进制中的1,表现的是A和B的不同的位。取第一个1所在的位数,假设是第index位,接着把原数组分成两组,分组标准是第index位是否为1。如此,相同的数肯定在一个组,因为相同数字所有位都相同,而不同的数,肯定不在一组。然后把这两个组按照最开始的思路,依次异或,剩余的两个结果就是这两个只出现一次的数字。
public class Solution { public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { if (array.length == 2) { num1[0] = array[0]; num1[1] = array[1]; } int bitResult = 0; for (int i = 0; i < array.length; i++) bitResult ^= array[i]; int index = findFirst1(bitResult); for (int i = 0; i < array.length; i++) { if (isBit1(array[i], index)) num1[0] ^= array[i]; else num2[0] ^= array[i]; } } private int findFirst1(int bitResult) { int index = 0; while ((bitResult & 1) == 0 && index < 32) { bitResult = bitResult >> 1; index++; } return index; } private boolean isBit1(int target, int index) { return ((target >> 1) & 1) == 1; }}
思路二:
import java.util.ArrayList;public class Solution { public static void main(String[] args) { Solution s = new Solution(); int[] array = {2,4,3,6,3,2,5,5}; int[] num1 = new int[1]; int[] num2 = new int[1]; s.FindNumsAppearOnce(array, num1, num2); } public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < array.length; i++) { if (!list.contains(array[i])) list.add(array[i]); else list.remove(new Integer(array[i])); } if (list.size() > 1) { num1[0] = list.get(0); num2[0] = list.get(1); } }}
思路三:
import java.util.HashMap;import java.util.Map;public class Solution { public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { HashMap<Integer, Integer> map = new HashMap<>(); num1[0] = num2[0] = 0; for (int i = 0; i < array.length; i++) { if (!map.containsKey(array[i])) map.put(array[i], 1); else map.replace(array[i],2); } for (Map.Entry<Integer, Integer> m : map.entrySet()) if (m.getValue() == 1) { if (num1[0] == 0) num1[0] = m.getKey(); else num2[0] = m.getKey(); } }}
阅读全文
0 0
- 数组中只出现一次的数字(数组)
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 数组中只出现一次的数字
- 单例封装retrofit+拦截器
- Maven实战
- webview运用和传值
- 多线程下载
- HDU 1257 最少拦截系统
- 数组中只出现一次的数字(数组)
- IjkMediaPlayer
- Smallest Difference(最小差值)三种角度求解
- Java基础总结第(3)天
- spring+mybatis的配置用法
- 第13周项目1-(1)验证折半查找算法
- 6. 二维数组和面向对象
- shell script中read的用法
- 设计模式系列-面向对象葵花宝典-面向对象实战