16. 3Sum Closest
Medium
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
solution:找到三个相加和target最相近的数字。本质上和15题思路一样。让第一个数字先定下来,然后后面两个数字从两端开始
向中间循环,在这个题卡了因为一些简单的问题卡了好久。 这里不能随便对两端的指针进行++/--因为 这不同于相加等于0, ++或者--可能会丢失某个数字
代码如下:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res=nums[0] + nums[1] + nums[2];;
int closest=INT_MAX ;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
int newDiff = abs(sum - target);
if (closest > newDiff) {
closest = newDiff;
res = sum;
}
if(sum<target)
++left;
else --right;
}
}
return res;
}
};
17.17. Letter Combinations of a Phone Number
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
solution:考虑给每个数字都做一个字典,然后递归调用每个数字就可以了,
这里稍微说一下递归函数:先写递归出口。然后再写递归
代码实现如下:
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
vector<string> res;
string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinationsDFS(digits, dict, 0, "", res);
return res;
}
void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) {
if (level == digits.size()) {res.push_back(out); return;}
string str = dict[digits[level] - '0'];
for (int i = 0; i < str.size(); ++i) {
letterCombinationsDFS(digits, dict, level + 1, out + string(1, str[i]), res);
}
}
};
18. 4Sum
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
solution:和3sum基本类似,遍历循环,先确定前两个数字。 后两个数字从两端开始向中间递归。
这里需要先用set<vector<int>>。因为四个数字不能保证没有重复。(第一个和第二个可能重复)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> res;
sort(nums.begin(),nums.end());
for (int i = 0; i < int(nums.size() - 3); ++i) {
for (int j = i + 1; j < int(nums.size() - 2); ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int left = j + 1, right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
vector<int> out{nums[i], nums[j], nums[left], nums[right]};
res.insert(out);
++left; --right;
} else if (sum < target) ++left;
else --right;
}
}
}
return vector<vector<int>>(res.begin(),res.end());
}
};
19.Remove Nth Node From End of List
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
solution:删除从结尾开始数的第n个数字,希望能一次循环就删去,需要绑定一个前指针,让后指针先移动n次,这样再一起移动,当后指针移动到结尾时,前指针则为倒数第N个
代码略去
20.Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
solution:检测括号是否成对匹配,最直接的想法就是遇到左括号,就压入栈,遇到右括号,看栈顶是不是对应的左括号,如果是出栈,如果不是,返回false。最后检查栈是否为空,如果空则匹配,否则返回false