Created
May 3, 2022 06:48
-
-
Save vimalvk9/29141773f523861b57c6e07d862b81ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int findUnsortedSubarray(vector<int>& nums) { | |
vector<int> newNums; | |
for (int num: nums) { | |
newNums.push_back(num); | |
} | |
sort(newNums.begin(), newNums.end()); | |
int firstMismatchIdx = -1; | |
int lastMismatchIdx = -1; | |
for(int i=0; i<nums.size(); i++) { | |
if (nums[i] != newNums[i]) { | |
if (firstMismatchIdx == -1) { | |
firstMismatchIdx = i; | |
} | |
lastMismatchIdx = i; | |
} | |
} | |
if (firstMismatchIdx == -1 && lastMismatchIdx == -1) { | |
return 0; | |
} | |
return (lastMismatchIdx - firstMismatchIdx + 1); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment