Description:
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.
For example, if target == ‘z’ and letters == [‘a’, ‘b’], the answer is ‘a’.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target
Solution_1
traverse all elements in array and find the smallest character in non-decreasing order sorted arrray
The results of my codes:
The smallest character in the array that is larger than d is f
The corresponding codes:
#include <iostream>
#include <vector>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::max;
using std::vector;
using std::setw;
char nextGreatestLetter(vector<char>& letters, char target);
int main()
{
vector<char> letters{'c','f','j'};
char target = 'd';
char result = nextGreatestLetter(letters, target);
cout << "The smallest character in the array that is larger than " << target << " is " << result << endl;
return 0;
}
char nextGreatestLetter(vector<char>& letters, char target)
{
for (char letter : letters){
if (letter > target) return letter;
}
return letters[0];
}
Solution_2
==Just use binary search method to find the ==
The codes:
#include <iostream>
#include <vector>
#include <iomanip>
#include <bits/stdc++.h>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::max;
using std::vector;
using std::setw;
char nextGreatestLetter(vector<char>& letters, char target);
int main()
{
vector<char> letters{'c','f','j'};
char target = 'd';
char result = nextGreatestLetter(letters, target);
cout << "The smallest character in the array that is larger than " << target << " is " << result << endl;
return 0;
}
char nextGreatestLetter(vector<char>& letters, char target)
{
return target < letters.back() ? *upper_bound(letters.begin(), letters.end() - 1, target) : letters[0];
}
If you want to find know the meaning of upper_bound() or basic utility ways, you could click it.
|