zoukankan      html  css  js  c++  java
  • 找出数组中只出现一次的唯一值

    // Example program
    #include <iostream>
    #include <string>
    
    int main()
    {
      int a[9] = {109,239,3432,8981,-7,109,239,3432,8981};
      int ans = 0;
      for(auto t : a) {
          ans^=t;
      }
      std::cout<<ans<<std::endl;
      return 0;
    }
    

    使用异或运算符将相同的变量一一消去

    #include <iostream>
    using namespace std;
    
    int find_2_1_2(int n, int* a)
    {
        int i;
        int ans=0;
        int ans1=0, ans2=0;
        for(i=0;i<n;i++)
            ans^=a[i];
        std::cout<<"xor all : " << ans<< std::endl;
        int pos=0;
        while(((ans>>pos)&1) != 1)
            pos++;
    
        std::cout<<"Pose is : "<<pos<<std::endl;
        for(i=0;i<n;i++)
        {
            if(((a[i] >> pos)&1)!=1)
                ans1 ^= a[i];
            else
                ans2 ^= a[i];
        }
        cout<<ans1<<"
    "<<ans2<<endl;
        return 0;
    }
    
    int main() {
        int* vec = new int[100];
        for(int i = 0; i < 98; i+=2) {
            vec[i] = 2*i + i;
            vec[i + 1] = 2*i + i;
        }
        vec[98] = -100;
        vec[99] = -98;
        find_2_1_2(100, vec);
        delete[] vec;
        return 0;
    }
    

    实现找出两个只出现一次的值,使用异或找出不相同的位,分成两组,分别进行.

  • 相关阅读:
    ios资源
    学习swift开源项目
    学习di'z地址
    IOS基础库
    IT自学论坛
    HVTableView 分享组
    IOS中的动画菜单
    iOS 通讯录操作
    ios中autolayout
    ios 程序学习
  • 原文地址:https://www.cnblogs.com/walnuttree/p/13541300.html
Copyright © 2011-2022 走看看