Single_Number_III
来源:互联网 发布:数据库crs 编辑:程序博客网 时间:2024/06/03 10:01
题目描述:
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice.
Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
(鉴于数字数组数组,其中两个元素只出现一次,其他所有元素的出现正是两次。查找只出现一次的两个元素。)
思路:模仿Single_Number,将所有数异或,但有一点不同的是这回有两个只出现一次数,所以这次得到的值就是这两个数的异或值,在得到的这个异或值的二进制表达中为1的位就是两个数不相同的位,例如2(0010)和7(0111)异或得5(0101),利用这一点就可以从原数组中分离出两个数来。将异或值的从低位到高位的第一个1保留,剩下的位全为0,再用这个经过改变的异或值分离两个不同的数,例如刚刚得到异或值5(0101),经过改变之后变为1(0001),再和2与7分别相与得0和1,这样就分离出了两个数,实质上就是将nums数组分为两个Single_Number_I数组,再利用Single_Number_I的方法解决。
public class Single_Number_III {public static int[] singleNumber(int[] nums){int result[] = new int[2];if(nums.length==0)return result;int mid = 0;for(int i=0;i<nums.length;i++){mid ^= nums[i];}//这是一个很巧妙的办法网上看到的,作用是将异或值的从低位到高位的第一个1保留,剩下的位全为0mid &= -mid;for(int i=0;i<nums.length;i++){if((mid&nums[i])==0){result[0] ^= nums[i];}else{result[1] ^= nums[i];}} return result; }public static void main(String[] args) {int nums[] = {1, 2, 1, 3, 2, 5};int result[] = singleNumber(nums);System.out.println(result[0]+" "+result[1]);}}
- Single_Number_III
- Java9 接口支持私有方法
- sem_wait & sem_post
- ubuntu 16.04环境下安装gnuradio+UHD
- 【教程】设置友链转到大佬博客方法√
- rdd 操作的回调函数中不允许有其他rdd的操作
- Single_Number_III
- 关于Freemarker模板报错的问题
- Nio总结之Channel与Buffer
- 请定义一个交通工具(Vehicle)的类
- spark streaming 从kafka拉数据限速
- 编译libcef_dll_wrapper.lib
- 01-SpringBoot的三种启动方式
- TensorFlow深度学习
- 点到平面的距离