TypechoJoeTheme

IT技术分享

统计

[LeetCode 136] Single Number [Java] [Runtime : 1MS]

2017-08-31
/
0 评论
/
637 阅读
/
正在检测是否收录...
08/31

1. Description

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. Runtime Distribution

3. Submission Details

4. Example

Input: 14,14,23,35,23
Ouput: 35

5. Code

public int singleNumber(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int result = nums[0];
    for (int i = 1; i < nums.length; i++) {
        result ^= nums[i];
    }
    return result;
}

6.Test

public class LeetCode0136 {
    public int singleNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            result ^= nums[i];
        }
        return result;
    }

    public static void main(String[] args) {
        LeetCode0136 leetcode = new LeetCode0136();
        int[] nums = { 14, 14, 23, 35, 23 };
        System.out.println(leetcode.singleNumber(nums));
    }
}
BIT
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/748/(转载时请注明本文出处及文章链接)