欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

牛客题霸-数组中只出现一次的数字题解

程序员文章站 2022-03-08 15:51:53
...

题目链接:https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=188&rp=1&ru=%2Fta%2Fjob-code-high-week&qru=%2Fta%2Fjob-code-high-week%2Fquestion-ranking

排序+暴力枚举

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        sort(data.begin(),data.end());
        int top;
        for(int i=0;i<data.size();i++){
            int val=data[i];
            int flag=0;
            if(i-1>=0&&data[i-1]==val)flag=1;
            if(i+1<data.size()&&data[i+1]==val)flag=1;
            if(flag==0){
                *num1=val;
                top=val;
                break;
            }
        }
        for(int i=0;i<data.size();i++){
            if(data[i]==top)continue;
            int val=data[i];
            int flag=0;
            if(i-1>=0&&data[i-1]==val)flag=1;
            if(i+1<data.size()&&data[i+1]==val)flag=1;
            if(flag==0){
                *num2=val;
                break;
            }
        }
    }
};