본문 바로가기
개발/코딩

해커랭크(HackerRank) - Almost Sorted // C++

by lucidmaj7 2021. 5. 19.
728x90
반응형

https://www.hackerrank.com/challenges/almost-sorted/problem

 

Almost Sorted | HackerRank

Sort an array by either swapping or reversing a segment

www.hackerrank.com

 

void segmentSort(vector<int>* arr, int from, int to)
{
    sort(arr->begin()+from, arr->begin()+to+1);
}

bool isASC(vector<int> arr, int from, int to)
{
    int prev = arr[from];
 
    for(int i = from+1; i<= to;i++)
    {  
        if(prev > arr[i])
        {
            return false;
        }
        prev = arr[i];
    }
    return true;
}
bool isDESC(vector<int> arr, int from, int to)
{
    int prev = arr[from];

    for(int i = from+1; i<= to;i++)
    {
      
        if(prev< arr[i])
        {
            return false;
        }
        prev = arr[i];
    }
    return true;
}
void almostSorted(vector<int> arr) {
    vector<int> peakValley;
    if(isASC(arr, 0 , arr.size()-1))
    {
        cout<< "yes" << endl;
        return;
    }
    if(arr.size() == 2)
    {
        cout <<"yes" << endl <<"swap 1 2" << endl;
        return;
        
    }
    if(isDESC(arr, 0 , arr.size()-1))
    {
        cout<< "yes" << endl;
        cout<< "reverse " << 1 << " " << arr.size()<<endl;
        return;
    }
    
    for(int i = 1; i<arr.size()-1;i++)
    {
    
        if(
            (arr[i-1] < arr[i] && arr[i] > arr[i+1])
            ||
            (arr[i-1] > arr[i] && arr[i] < arr[i+1])
          )
        {
           peakValley.push_back(i);
        }
    }
    
    if(peakValley.size()>=2)
    {
        string operation = "reverse";
        if(arr[*peakValley.begin()] > arr[*peakValley.end()-1])
        {
            
            if(isASC(arr,*(peakValley.begin())+1,*(peakValley.end()-1)-1) 
            ||*(peakValley.end()-1) - *(peakValley.begin()) == 1
                )
            {
            
                operation = "swap";
            }else if(!isDESC(arr,*(peakValley.begin())+1,*(peakValley.end()-1)-1) )
            {
                goto EXIT;
            }
            
            segmentSort(&arr,*(peakValley.begin()),*(peakValley.end()-1));
             
            if(isASC(arr, 0 , arr.size()-1))
            {
             cout<< "yes" <<endl << operation <<" " << *(peakValley.begin())+1 <<" "<<*(peakValley.end()-1)+1<< endl;
              return;
            }else {
                
                goto EXIT;
            }
            
            
        }
    }
  
EXIT:
   cout<<"no"<<endl;
    return;
    

}

참고

https://medium.com/@leejh3224/hackerrank-solution-almost-sorted-4331bd58275

728x90
반응형

'개발 > 코딩' 카테고리의 다른 글

백준 - ATM - Swift  (0) 2022.07.10
백준 - 설탕 배달 - Swift  (0) 2022.07.10
해커랭크(HackerRank) - The Grid Search // C++  (0) 2021.05.16
[hackerrank] Minimum Absolute Difference in an Array / C++  (0) 2020.12.07
LeetCode - Two Sum / c++  (0) 2020.07.24

댓글