leetcode--single number.

来源:互联网 发布:mysql如何创建存储过程 编辑:程序博客网 时间:2024/06/06 04:15

问题地址: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?

你的算法时间复杂度应该是线性,即O(n),你可以不使用额外的空间实现它么?

由于我自己的算法时间复杂度为O(n^2),不符合要求。之后在讨论区看到了优秀的算法。利用异或的特性A^B^A=B。

public int singleNumber(int[]A){    int result = 0;    for (int i = 0; i<A.length; i++)    {        result ^=A[i];    }    return result;}
另外可以先排序,因为排序的时间复杂度可以达到O(nlogn),虽然不符合要求。。。

0 0
原创粉丝点击