p136

LeetCode P136 Single Number 题解

1.题目:

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Subscribe to see which companies asked this question

题意:

输入一个数组,返回这个数组中单出来的那个数,希望只做一次循环不占用其它空间

2.解题思路:

java 位运算的^亦或:二进制每位相同则结果为0,不同则结果为1。
由定义可以知道:0^n=n,n^n=0;

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
package leetcode;

import java.util.Scanner;


/**
*
* @author ZhangMengRou
*
*/
public class p292 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();
String[] list = a.split(" ");
int[] al = new int[list.length];
for (int i=0;i<list.length;i++)
{
al[i]=Integer.parseInt(list[i]);
}
int ans = singleNumber(al);
System.out.print(ans);
}

public static int singleNumber(int[] nums) {

int as = 0;
for (int i = 0; i < nums.length; i++) {
as = as ^ nums[i];
}
return as;

}

}



4.一些总结:

有时候位运算是一个不错的选择~不过好像就知道这一种符合要求的方法,
希望可以找到新的方法补充。