【LeetCode】Single Number

Single Number 
Total Accepted: 19208 Total Submissions: 42682 My Submissions
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?
【解题思路】
两个相同元素异或的结果为0。
因为数组中其他元素都出现2次,只有一个出现1次,所以循环整个数组,依次异或,结果就应该是那个只出现1次的数字。
Java AC 352ms

public class Solution {
    public int singleNumber(int[] A) {
        if(A == null || A.length == 0 ){
            return 0;
        }
        int result = A[0];
        for(int i = 1; i < A.length; i++){
            result ^= A[i];
        }
        return result;
    }
}

update 2014-06-10(增加python)
Python AC 284ms

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        alen = len(A)
        result = A[0]
        for i in range(1, alen, 1):
            result ^= A[i]
        return result
这个题目其实和九度上的 题目1256:找出两个只出现了一次的数字有点类似。

不同之处在于1256比这个难度上升了一点。有两个数字出现一次,其他都出现两次。
根据这个题目的思路,如果我们能将原数组分为两个数组,每个数组中只有一个数字出现一次,其他都出现两次就好办多了。
怎么分呢。
和这个题目一样,先将整个数组异或一次,那么结果就是各出现一次的那两个数字的异或结果。
因为这两个数字不相同,所以异或结果一定不为0,那么用2进制表示的这个数中必然有1位为1。
我们找出这个结果中第一次出现1的位置index,根据1的位置,将原数组分为两个子数组。
一个数组的index位全部为0,另一个全部为1,那么再次异或就得到了两个数字。
Java AC

import java.io.StreamTokenizer;
 
public class Main {
    /*
     * 1256
     */
    public static void main(String[] args) throws Exception {
        StreamTokenizer st = new StreamTokenizer(System.in);
        while (st.nextToken() != StreamTokenizer.TT_EOF) {
            int N = (int) st.nval;
            int[] array = new int[N];
            int result = 0;
            for (int i = 0; i < N; i++) {
                st.nextToken();
                array[i] = (int) st.nval;
                result ^= array[i];
            }
  
            int num = 0;
            while ((result & 1) == 0) {
                result = result >> 1;
                num++;
            }
            int num1 = 0;
            int num2 = 0;
            for (int i = 0; i < N; i++) {
                if (((array[i] >> num) & 1) == 0) {
                    num1 ^= array[i];
                } else {
                    num2 ^= array[i];
                }
            }
            if (num1 > num2) {
                System.out.println(num2 + " " + num1);
            } else {
                System.out.println(num1 + " " + num2);
            }
        }
    }
}
/**************************************************************
    Problem: 1256
    User: wangzhenqing
    Language: Java
    Result: Accepted
    Time:770 ms
    Memory:33104 kb
****************************************************************/

LeetCode算是除九度之外的另一个开始吧。加油。

你可能感兴趣的:(java,LeetCode,python)