LeetCode: Remove Element
14104 ワード
Question
Core Logic
Intuitive Logic
vector.erase()
's time complexity, worst case would take O(N) for each single erase operation. Bit more optimized Logic && Algorithm
Code
class Solution {
public:
void getStartRange(int& container, int middleIndex, int& target, vector<int>& nums) {
container = -1;
while (middleIndex >= 0) {
if (nums[middleIndex] != target) {
container = middleIndex+1;
break;
}
middleIndex--;
}
if (container == -1) container = 0;
}
void getEndRange(int& container, int middleIndex, int& target, vector<int>& nums) {
container = -1;
while (middleIndex < nums.size()) {
if (nums[middleIndex] != target) {
container = middleIndex-1;
break;
}
middleIndex++;
}
if (container == -1) container = nums.size()-1;
}
int removeElement(vector<int>& nums, int val) {
if (nums.empty()) {
return 0;
}
sort(nums.begin(), nums.end());
int start = 0;
int end = nums.size()-1;
int middleIndex = (start + end) / 2;
int eraseStart = -1;
int eraseEnd = -1;
while (start <= end) {
middleIndex = (start + end) / 2;
if (nums[middleIndex] < val) {
// Right
start = middleIndex+1;
} else if (nums[middleIndex] > val) {
// Left
end = middleIndex-1;
} else {
// Same
getStartRange(eraseStart, middleIndex, val, nums);
getEndRange(eraseEnd, middleIndex, val, nums);
break;
}
}
if (eraseStart != -1 && eraseEnd != -1) {
nums.erase(nums.begin()+eraseStart, nums.begin()+eraseEnd+1);
}
return nums.size();
}
};
Submission
Reference
この問題について(LeetCode: Remove Element), 我々は、より多くの情報をここで見つけました https://velog.io/@kangdroid/LeetCode-Remove-Elementテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol