0
0

XOR演算を使用して解く LeetCode Single Number

Posted at

問題文

空でない整数 nums の配列では、1 つを除いてすべての要素が 2 回出現します。その 1 つを見つけてください。

実行時の複雑さが線形になるソリューションを実装し、一定の追加スペースのみを使用する必要があります。

解答

上記問題のポイントは、同じ数を確認できるかどうかです。
XOR演算^を使用することにより、可能になります。
なぜなら、XOR演算では同じ数があった場合0になり、被っていない数は残るからです。

コード java

class Solution {
    public int singleNumber(int[] nums) {
       int result = 0;
       for (int n : nums){
           result^=n;
       } 
        System.gc();
       return result;
    }
}

実行時間:2ms
メモリー:42.74

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0