167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Solution in C++:
关键点:
- 下标从1开始
思路:
- 其实就是变形的二分查找,一个数固定,target-数就是在剩下数中需要查找的数,并且有序数组这个提示就是二分的一个标志。
- 看了讨论中的一些代码,由于题目本身规定了解唯一,所以可以直接采取一次二分的方式。
int find(vector<int>& numbers, int start, int end, int target){
while(start <= end){
int mid = (start + end) / 2;
if(target == numbers[mid])
return mid;
else if (target > numbers[mid]){
start = mid + 1;
} else{
end = mid - 1;
}
}
return -1;
}
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> result;
size_t size = numbers.size();
for( int i = 0; i < size; ++i){
int tmp = find(numbers, i + 1, size - 1, target - numbers[i]);
if (tmp != -1){
result.push_back(i+1);
result.push_back(tmp+1);
}
}
return result;
}
168. Excel Sheet Column Title
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"
Solution in C++:
关键点:
- (0-25)对应(‘A’-‘Z’)
思路:
- 开始拿到有点懵,一看再一想好像就是26进制的问题,搞好字母与数字间的对应关系这题就比较容易做出来了。
string convertToTitle(int n) {
vector<char> table{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
string strR = "";
--n;
while(n >= 0){
strR += table[n%26];
n = n / 26 - 1;
}
reverse(strR.begin(),strR.end());
return strR;
}
169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Solution in C++:
关键点:
- 元素出现的次数
思路:
- 第一个想法是暴力,计数,达到一半及以上就为所求。后来想了一下概率问题,但是具体实施感觉应该也不简单。
- 后来去看了解析,里面有一个Boyer-Moore Voting Algorithm,觉得思路还是蛮有意思的。大多数元素一定是和其他元素抵消之后剩下的。
int majorityElement(vector<int>& nums) {
int count = 0;
int candidate;
for(auto num : nums){
if (count == 0){
candidate = num;
}
count += (num == candidate)?1:-1;
}
return candidate;
}
小结
今天整个人状态不是很好,但是刷题的状态还行,前两题还是比较好做的,第三题除了暴力外的其他方法思路还不错,比如Boyer-Moore Voting Algorithm,让我们在看到这种题目的时候思考,数学上的关系。
知识点
- Boyer-Moore Voting Algorithm