@XQF
2018-03-07T14:56:50.000000Z
字数 1549
阅读 1117
数据结构与算法
一个整型数组中,除了一个数只出现了一次之外其他数均出现了两次。
a^a=0;
0^b=b;
这种方法对于偶数次有用,奇数的话就么有办法了
public class Solution {public int findNotDouble(int[] nums) {if(nums==null||nums.length){return -1;}int result = 0;for (int i : nums) {result ^= i;}System.out.println("result:" + result);return result;}public static void main(String[] args) {Solution solution = new Solution();int[] nums = {2, 2, 3};solution.findNotDouble(nums);}}
这是3次的情况,至于次数可以用counter控制
public class Solution {public int findNotDouble(int[] nums) {if (nums == null || nums.length == 0) {return -1;}Arrays.sort(nums);int counter = 0;for (int i = 0; i < nums.length - 1; i++) {if (nums[i] == nums[i + 1]) {counter++;} else {if (counter == 2) {if (i == nums.length - 2) {return nums[nums.length - 1];}counter = 0;} else {return nums[i];}}}return 0;}public static void main(String[] args) {Solution solution = new Solution();int[] nums = {2, 2, 2, 5, 5, 5, 6, 6, 6, 9};System.out.println("result: " + solution.findNotDouble(nums));}}
思想就是统计1的个数,。,一直在思考如何得出这个数字,。原来根据不符合条件位置直接加和就可以了
public class Solution {public int findNotDouble(int[] nums, int k) {if (nums == null || nums.length == 0) {return -1;}int[] counteOne = new int[32];int counter = 1;for (int i = 0; i < 32; i++) {for (int j = 0; j < nums.length; j++) {if ((counter & nums[j]) != 0) {counteOne[i]++;}}counter <<= 1;}int result = 0;for (int i = 0; i < counteOne.length; i++) {if (counteOne[i] % k != 0) {result += 1 << i;}}return result;}public static void main(String[] args) {Solution solution = new Solution();int[] nums = {2, 2, 2, 3, 5, 5, 5, 6, 6, 6};System.out.println("result: " + solution.findNotDouble(nums, 3));}}
返回-1假设均是正整数的情况下,实际上负数也行,但是不和题意得返回就要看题意了
