zoukankan      html  css  js  c++  java
  • LeetCode136: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?

    解题思路:

    很简单的一题,直接用异或运算解决:连个相同数进行异或结果为0,0与任何数异或结果为原数

    也可先进行排序再遍历排序后的数组,当某个数没有重复时,结果就是它了

    也可用bitmap进行,不多说了。

    实现代码:

    #include <iostream>
    
    using namespace std;
    /*
    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?
    */
    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int ret = 0;
            for(int i = 0; i < n; i++)
                ret ^= A[i];
            return ret;
            
        }
    };
    
    int main(void)
    {
        int arr[] = {2,4,5,5,4,1,2};
        int len = sizeof(arr) / sizeof(arr[0]);
        Solution solution;
        int once = solution.singleNumber(arr, len);
        cout<<once<<endl;
        return 0;
    }
  • 相关阅读:
    postgresql删除活动链接的数据库
    第四篇 函数
    Jmeter响应中文乱码解决办法
    第三篇 条件控制和循环
    第二篇 Python运算符
    npm更换为镜像
    第一篇 Python的数据类型
    newman的常用命令使用总结
    windows下安装newman
    同态包络提取
  • 原文地址:https://www.cnblogs.com/mickole/p/3673529.html
Copyright © 2011-2022 走看看