[LeetCode] 136. Single Number

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

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,1]
Output: 1
Example 2:

Input: nums = [4,1,2,1,2]
Output: 4
Example 3:

Input: nums = [1]
Output: 1

Constraints:

1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Each element in the array appears twice except for one element which appears only once.

思路

用的是异或的性质,没想到啊!!!

代码

class Solution {
    public int singleNumber(int[] nums) {
        int single = 0;
        for (int num : nums) {
            single ^= num;
        }
        return single;
    }
}

欢迎转载,转载请注明出处!

推荐这些文章:

LeetCode 1056. Confusing Number

原题链接在这里:https://leetcode.com/problems/confusing-number/
题目:
Given a number N, return true if and only if it is a confusing number, which satisfies th...

[leetcode] 136. Single Number

题目
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:

Note that in some languages, such...

LeetCode 0065 Valid Number

原题传送门
1. 题目描述

2. Solution 1
1、思路分析
All we need is to have a couple of flags so we can process the string in liner time:
We start with trimming.
If we see [0-9] we rese...

LeetCode 912. Sort an Array

原题链接在这里:https://leetcode.com/problems/sort-an-array/
题目:
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Outp...

LeetCode 0078 Subsets

原题传送门
1. 题目描述

2. Solution 1
**1、思路分析 **
递归使用回溯法。

2、代码实现
package Q0099.Q0078Subsets;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
impor...

[leetcode] 202. Happy Number

题目
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:

Starting with any positive integer, replace the ...

LeetCode 796. Rotate String

原题链接在这里:https://leetcode.com/problems/rotate-string/
题目:
We are given two strings, A and B.
A shift on A consists of taking string A&n...

LeetCode 0075 Sort Colors

原题传送门
1. 题目描述

2. Solution 1
1、思路分析
类似快排思想,把所有的0放到数组头部,把所有2放到数组尾部,这样1全部留在中间。
2、代码实现
package Q0099.Q0075SortColors;

public class Solution {
/*
The idea is to ...

LeetCode 390. Elimination Game

原题链接在这里:https://leetcode.com/problems/elimination-game/
题目:
There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and...

540. Single Element in a Sorted Array

这道题如果用暴力解法做非常简单,但是题目有要求:Your solution must run in O(log n) time and O(1) space.
如果看到时间复杂度O(logn),那么就一定要想到binary search。需要注意的是,在做这类找数题的时候,一定要看清楚是让返回in...

文章标题:[LeetCode] 136. Single Number
文章链接:https://www.dianjilingqu.com/50941.html
本文章来源于网络,版权归原作者所有,如果本站文章侵犯了您的权益,请联系我们删除,联系邮箱:saisai#email.cn,感谢支持理解。
THE END
< <上一篇
下一篇>>