[HackerRank] LonelyInteger

jh Seo·2024년 2월 4일
0

HackerRank

목록 보기
4/15

개요

[HackerRank] LonelyInteger

Given an array of integers, where all elements but one occur twice, find the unique element.

접근 방식

unique한 원소 찾기 문제이다.
정렬해준 후, 각 원소마다 이전원소, 다음원소를 비교해 탐색하는 식으로 구현했다.

전체코드

int lonelyinteger(vector<int> a) {
    sort(a.begin(),a.end());
    if(a.size()==1) 
        return a[0];
    if(a[0] != a[1]){
        return a[0];
    }
    for(int i=1;i<a.size()-1;i++){
        if(a[i] != a[i-1] && a[i]!= a[i+1]){
            return a[i];
        }
    }
    if(a.back() != *(a.end()-2)){
        return a.back();
    }
    return -1;
}
profile
코딩 창고!

0개의 댓글