只出現一次的數字

原題

  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?算法

題目大意

  給定一個數組,每一個元素都出現2次除了其中的一個,找出只出現一次的數字注意:算法必須是線性時間複雜度,能夠不使用額外空間實現嗎?數組

解題思路

  使用異或運算。app

代碼實現

算法實現類spa

public class Solution {

    public int singleNumber(int[] nums) {

        if (nums == null || nums.length < 1) {
            throw new IllegalArgumentException("nums");
        }


        for (int i = 1; i< nums.length; i++) {
            nums[0] ^= nums[i];
        }
        return nums[0];
    }
}
相關文章
相關標籤/搜索