leetcode 题解代码整理 16-20题
3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int ans,i,j,l,r,mid; sort(nums.begin(),nums.end()); ans=20000000; for (i=0;i<nums.size()-2;i++) for (j=i+1;j<nums.size()-1;j++) { l=j+1; r=nums.size()-1; if (nums[i]+nums[j]+nums[r]<target) { if (abs(nums[i]+nums[j]+nums[r]-target)<abs(ans-target)) ans=nums[i]+nums[j]+nums[r]; continue; } if (nums[i]+nums[j]+nums[l]>target) { if (abs(nums[i]+nums[j]+nums[r]-target)<abs(ans-target)) ans=nums[i]+nums[j]+nums[l]; continue; } while (l<=r) { mid=(l+r)/2; if (abs(ans-target)>abs(nums[i]+nums[j]+nums[mid]-target)) ans=nums[i]+nums[j]+nums[mid]; if (ans==target) break; if (nums[i]+nums[j]+nums[mid]<target) l++; else r--; } if (ans==target) break; } return ans; } };
Letter Combinations of a Phone Number
Given a digit string, 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.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution { vector<string>ans; string mark; int len; public: vector<string> letterCombinations(string digits) { len=digits.length(); ans.clear(); if (len==0) return ans; mark=digits; dfs(0,""); return ans; } private: void dfs(int k,string ch) { if (k==len) { ans.push_back(ch); return ; } if (mark[k]=='2'){dfs(k+1,ch+"a"); dfs(k+1,ch+"b"); dfs(k+1,ch+"c");} if (mark[k]=='3'){dfs(k+1,ch+"d"); dfs(k+1,ch+"e"); dfs(k+1,ch+"f");} if (mark[k]=='4'){dfs(k+1,ch+"g"); dfs(k+1,ch+"h"); dfs(k+1,ch+"i");} if (mark[k]=='5'){dfs(k+1,ch+"j"); dfs(k+1,ch+"k"); dfs(k+1,ch+"l");} if (mark[k]=='6'){dfs(k+1,ch+"m"); dfs(k+1,ch+"n"); dfs(k+1,ch+"o");} if (mark[k]=='7'){dfs(k+1,ch+"p"); dfs(k+1,ch+"q"); dfs(k+1,ch+"r"); dfs(k+1,ch+"s");} if (mark[k]=='8'){dfs(k+1,ch+"t"); dfs(k+1,ch+"u"); dfs(k+1,ch+"v");} if (mark[k]=='9'){dfs(k+1,ch+"w"); dfs(k+1,ch+"x"); dfs(k+1,ch+"y"); dfs(k+1,ch+"z");} } };
4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {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)枚举前两个数字,然后用2sum的思路
class Solution
{
public:
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
sort(nums.begin(),nums.end());
vector<vector<int> >ans;
if (nums.size()<4) return ans;
set<string>st;
for (int i=0;i<nums.size()-3;i++)
for (int j=i+1;j<nums.size()-2;j++)
{
int l=j+1;
int r=nums.size()-1;
int sum=nums[i]+nums[j];
while (l<r)
{
int temp=nums[l]+nums[r];
if (sum+temp==target)
{
string str;
str+=nums[i];
str+=nums[j];
str+=nums[l];
str+=nums[r];
set<string>::iterator it=st.find(str);
if (it==st.end())
{
st.insert(str);
vector<int>mark;
mark.clear();
mark.push_back(nums[i]);
mark.push_back(nums[j]);
mark.push_back(nums[l]);
mark.push_back(nums[r]);
ans.push_back(mark);
}
l++;
r--;
}
else
if (sum+temp<target)
l++;
else
r--;
}
}
return ans;
}
};
Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
链表处理经典面试题
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL)
return NULL;
ListNode *pPre = NULL;
ListNode *p = head;
ListNode *q = head;
for(int i = 0; i < n - 1; i++)
q = q->next;
if (q->next==NULL)
{
head=head->next;
return head;
}
while(q->next)
{
pPre = p;
p = p->next;
q = q->next;
}
pPre->next = p->next;
delete p;
return head;
}
};
Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
,
determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are
all valid but "(]"
and "([)]"
are
not.
class Solution { public: bool isValid(string s) { stack<char>st; int len=s.length(); for (int i=0;i<len;i++) if (s[i]=='(' || s[i]=='{' || s[i]=='[') st.push(s[i]); else { if (st.size()==0) return false; char ch=st.top(); st.pop(); if ( (ch=='(' && s[i]==')') || (ch=='[' && s[i]==']') || (ch=='{' && s[i]=='}') ); else return false; } if (st.size()==0) return true; else return false; } };