【LeetCode】#136只出現一次的數字(Single Number)
阿新 • • 發佈:2018-12-20
【LeetCode】#136只出現一次的數字(Single Number)
題目描述
給定一個非空整數陣列,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。
說明:
你的演算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
示例
示例 1:
輸入: [2,2,1]
輸出: 1
示例 2:
輸入: [4,1,2,1,2]
輸出: 4
Description
Given a non-empty 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?
Example
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
解法
class Solution { public int singleNumber(int[] nums) { int result = 0; for(int i=0; i<nums.length; i++){ result ^= nums[i]; } return result; } }