leetcode之Single Number

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">LeetCode官网网址:https://leetcode.com</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">本题网址:https://leetcode.com/problems/single-number/</span>

题目:

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?
Subscribe to see which companies asked this question

题目大概意思就是找出这个数组中只出现一次而不是两次的数。本题要求时间复杂度为线性时间,并且不以增加内存来实现。

于是,有一种比较好的思路就是采用集合,将遇到的数字加进集合,当再次遇到时从集合中删掉这个数字,循环结束后,剩下的那个数就是答案。

嗯,上代码:

public class Solution {
    public int singleNumber(int[] nums) {
          HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (set.isEmpty())
                set.add(nums[i]);
            else if (set.contains(nums[i]))
                set.remove(nums[i]);
            else
                set.add(nums[i]);
        }
        Iterator<Integer> iterator = set.iterator();
        Integer result = 0;
        while (iterator.hasNext()) {
            result = iterator.next();
        }
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值