Single Number

原题: https://leetcode.com/problems/single-number/description/

题意: 给定一个整数数组,除一个元素只出现一次外,其余各元素均出现两次。找出那个只出现一次的元素。

约定:(1)你的算法应该满足线性时间复杂度。可以不使用额外的空间完成此题吗?

标签: single、此题、number、元素、两次、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • Bingo
    2017-08-14 17:34:21 1楼#1层
    Python:
    class Solution:
        # @param {integer[]} nums
        # @return {integer}
        def singleNumber(self, nums):
            ans = 0
            for num in nums:
                ans ^= num
            return ans
  • Bingo
    2017-08-14 17:35:13 2楼#1层
    Java:
    public class Solution {
        public int singleNumber(int[] A) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(A == null || A.length == 0){
                return 0;
            }
            int result = A[0];
            
            for(int i = 1; i < A.length; i++){
                result = result ^ A[i];
            }
            return result;
        }
    }
  • 回复
隐藏