【LeetCode】136. Single Number

Difficulty:easy

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/single-number/java

Given a non-empty array of integers, every element appears twice except for one. Find that single one.app

Note:ide

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

Example 1:ui

Input: [2,2,1]
Output: 1

Example 2:spa

Input: [4,1,2,1,2]
Output: 4

Intuition

use XOR ( ^ )code

 

Solution

    public int singleNumber(int[] nums) {
        int ans=0;
        for(int n : nums){
            ans=ans^n;
        }
        return ans;
    }

  

Complexity

Time complexity : O(n)
htm

Space complexity : O(1)blog

 

What I've learned

1. when meeting problems about duplicate, considering using XOR.

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索