leetcode — single-number

/**
 * Source : https://oj.leetcode.com/problems/single-number/
 *
 *
 * 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?
 *
 */
public class SingleNumber {

    /**
     * 数组中每个元素都有相同的两个,只有其中一个元素是只有一个的,找出这个元素
     * 1. 对数组排序,将arr[i] 和arr[i-1]、arr[i+1]进行比较,如果又都不相等,那么就是要找的元素
     * 2. 使用hash表,循环数组,判断hash表中是否有这个元素,如果有则删除hash表的元素,否则将当前元素加入hash表,最后hash表中剩下的是要找的元素
     * 3. 使用异或运算,xor,一个数和自身异或运算为0,x^x = 0, x^0 = x
     *
     * @param arr
     * @return
     */
    public int singleNumber (int[] arr) {
        int res = 0;
        for (int i = 0; i < arr.length; i++) {
            res ^= arr[i];
        }
        return res;
    }

    public static void main(String[] args) {
        SingleNumber singleNumber = new SingleNumber();
        System.out.println(singleNumber.singleNumber(new int[]{1,1,2,2,3}) + " == 3");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值