leetcode--14. single-number

2018-12-04  本文已影响0人  yui_blacks

题目:
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?
给定一个整数数组,除一个元素外,每个元素都会出现两次。找到那个数。
注意:
你的算法应该具有线性运行时复杂性。你能在不使用额外内存的情况下实现它吗?

思路:
根据异或运算的特点:

  1. 相同两数异或结果为0
  2. 0和一个数异或为那个数本身
public class Solution {
    public int singleNumber(int[] A) {
        int num = 0;
        for(int i = 0;i < A.length;i++){
            num ^= A[i];
        }
        return num;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读