-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Smallest ranges II, use sort to understand.
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class Solution { | ||
public: | ||
/** | ||
* @brief LCQ1: sequence of strings appeared on screen | ||
* Time: O(N^2), Space: O(1) | ||
* | ||
* @param target | ||
* @return vector<string> | ||
*/ | ||
vector<string> stringSequence(string target) { | ||
int len = target.size(); | ||
vector<string> ans; | ||
|
||
for (int i = 0; i < len; i++) { | ||
char ch = 'a'; | ||
|
||
while (target[i] - ch >= 0) { | ||
string temp = target.substr(0, i); | ||
temp += ch; | ||
ans.push_back(temp); | ||
|
||
ch++; | ||
} | ||
} | ||
|
||
return ans; | ||
} | ||
|
||
|
||
|
||
}; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
class Solution { | ||
public: | ||
/** | ||
* @brief LC910: Smallest Range II | ||
* Time: O(NlogN), Sort is O(NlogN), Space: O(1) | ||
* | ||
* @param nums | ||
* @param k | ||
* @return int | ||
*/ | ||
int smallestRangeII(vector<int>& nums, int k) { | ||
sort(nums.begin(), nums.end()); | ||
int ans = nums.back() - nums[0]; | ||
|
||
for (int i = 1; i < nums.size(); i++) { | ||
int mx = max(nums[i - 1] + k, nums.back() - k); | ||
int mn = min(nums[0] + k, nums[i] - k); | ||
ans = min(ans, mx - mn); | ||
} | ||
|
||
return ans; | ||
} | ||
}; |