LeetCode Algorithm
LeetCode Algorithm
原文出处:【LeetCode】
算法参考:【陈皓 coolshell】
1. Two Sum
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
6. ZigZag Conversion
7. Reverse Integer
8. String to Integer (atoi)
9. Palindrome Number
12. Integer to Roman
13. Roman to Integer
14. Longest Common Prefix
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
20. Valid Parentheses
22. Generate Parentheses
24. Swap Nodes in Pairs
26. Remove Duplicates from Sorted Array
27. Remove Element
28. Implement strStr()
31. Next Permutation
32. Longest Valid Parentheses
34. Search for a Range
35. Search Insert Position
1. Two Sum
/**********************************************************
** 1. Two Sum
** Given an array of integers, return indices of the two numbers such that they add up to a specific target.
** You may assume that each input would have exactly one solution, and you may not use the same element twice. ** Example:
** Given nums = [2, 7, 11, 15], target = 9,
** Because nums[0] + nums[1] = 2 + 7 = 9,
** return [0, 1].
**********************************************************/
#include <iostream>
#include <unordered_map>
#include <vector> using namespace std; vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> m;
vector<int> result; for (int i=; i<numbers.size(); ++i) {
if (m.find(numbers[i]) == m.end()) {
m[target-numbers[i]] = i;
}else {
result.push_back(m[numbers[i]]);
result.push_back(i);
break;
}
} return result;
} //-----example-----
int main(int argc, char **argv) {
vector<int> numbers = {, , , };
int target = ; vector<int> result = twoSum(numbers, target);
cout << "result[";
for (auto it=result.begin(); it!=result.end(); ++it) {
cout << *it;
if (it != result.end()-) {
cout << ", ";
}
}
cout << "]" << endl; return ;
} //-----output-----
//result[0, 1]
3.Longest Substring Without Repeating Characters
/**********************************************************
** 3.Longest Substring Without Repeating Characters
** Given a string, find the length of the longest substring without repeating characters.
**
** Examples:
** Given "abcabcbb", the answer is "abc", which the length is 3.
** Given "bbbbb", the answer is "b", with the length of 1.
** Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
**********************************************************/
#include <string>
#include <iostream>
#include <map> using namespace std; int lengthOfLongestSubstring(string s) {
int longestLen = ;
int lastRepeatPos = -;
map<char, int> matchCharacters; for (int i=; i<s.size(); ++i) {
if (matchCharacters.find(s[i]) != matchCharacters.end() && lastRepeatPos < matchCharacters[s[i]]) {
lastRepeatPos = matchCharacters[s[i]];
} if (i-lastRepeatPos > longestLen) {
longestLen = i-lastRepeatPos;
} matchCharacters[s[i]] = i;
} return longestLen;
} //-----example-----
int main(int argc, char ** argv) {
string s = "abcabcbb";
cout << s << ":" << lengthOfLongestSubstring(s) << endl; s = "bbbbb";
cout << s << ":" << lengthOfLongestSubstring(s) << endl; s = "pwwkew";
cout << s << ":" << lengthOfLongestSubstring(s) << endl; return ;
} //-----output-----
//abcabcbb:3
//bbbbb:1
//pwwkew:3
5. Longest Palindromic Substring
/**********************************************************
** 5. Longest Palindromic Substring
** Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
**
** Example:
** Input: "babad"
** Output: "bab"
**
** Note: "aba" is also a valid answer.
**
** Example:
** Input: "cbbd"
** Output: "bb"
**********************************************************/
#include <string>
#include <iostream>
#include <vector> using namespace std; string findPalindrom(string s, int left, int right) {
while (left>= && right<=s.size()- && s[left]==s[right]) {
left--;
right++;
} return s.substr(left+, right-left-);
} string longestPalindrom(string s) {
int n = s.size();
if (n <= ) return s; string longest;
string str;
for (int i=; i<n-; ++i) {
str = findPalindrom(s, i, i);
if (str.size() > longest.size()) {
longest = str;
} str = findPalindrom(s, i, i+);
if (str.size() > longest.size()) {
longest = str;
}
} return longest;
} //-----example-----
int main(int argc, char **argv) {
string s = "babad";
cout << s << " : " << longestPalindrom(s) << endl; s = "cbbd";
cout << s << " : " << longestPalindrom(s) << endl; return ;
} //-----output-----
//babad : bab
//cbbd : bb
6. ZigZag Conversion
/**********************************************************
** 6. ZigZag Conversion
** The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
**
** P A H N
** A P L S I I G
** Y I R
** And then read line by line: "PAHNAPLSIIGYIR"
** Write the code that will take a string and make this conversion given a number of rows:
**
** string convert(string text, int nRows);
** convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
**********************************************************/
#include <string>
#include <iostream>
#include <vector> using namespace std; string zigzagConvert(string s, int rows) {
if (rows<= || rows>=s.size()) return s; vector<string> r(rows);
int index = ;
int step = ;
for (int i=; i<s.size(); ++i) {
if (index == ) step = ;
if (index == rows-) step = -;
r[index] += s[i];
index += step;
} string result;
for (int i=; i<rows; ++i)
{
result += r[i];
} return result;
} //-----example-----
int main(int argc, char **argv) {
string s = "PAYPALISHIRING";
int rows = ; cout << s << "[" << rows << "]:" <<zigzagConvert(s, rows) << endl; return ;
} //-----output-----
//PAYPALISHIRING[3]:PAHNAPLSIIGYIR
7. Reverse Integer
/**********************************************************
** 7. Reverse Integer
** Reverse digits of an integer.
**
** Example1: x = 123, return 321
** Example2: x = -123, return -321
**
** click to show spoilers.
**
** Note:
** The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
**********************************************************/
#include <iostream> using namespace std; #define INT_MAX_VALUE 2147483647
#define INT_MIN_VALUE (-INT_MAX_VALUE-1) int reverseInterget(int x) {
int result = ;
int n = ; while (x != ) {
n = x%;
if (result>INT_MAX_VALUE/ || result <INT_MIN_VALUE/) {
return ;
} result = result*+n;
x /=;
} return result;
} //-----example-----
int main(int argc, char **argv) {
cout << "123 : " << reverseInterget() << endl;
cout << "-123 : " << reverseInterget(-) << endl;
cout << "1020 : " << reverseInterget() << endl;
cout << "2147483647 : " << reverseInterget() << endl;
cout << "-2147483648 : " << reverseInterget(-) << endl; return ;
} //-----output-----
//123 : 321
//-123 : -321
//1020 : 201
//2147483647 : 0
//-2147483648 : 0
8. String to Integer (atoi)
/**********************************************************
** 8. String to Integer (atoi)
** Implement atoi to convert a string to an integer.
**
** Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
**
** Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
**********************************************************/
#include <iostream>
#include <ctype.h> using namespace std; #define INT_MAX_VALUE 2147483647
#define INT_MIN_VALUE (-INT_MAX_VALUE-1) int stringToInterget(const char *str) {
if (str==nullptr || *str=='\0') {
return ;
} int ret = ;
for (; isspace(*str); str++); bool bNeg = false;
if (*str=='-' || *str=='+') {
bNeg = (*str=='-');
str++;
} for (; isdigit(*str); str++) {
int digit = (*str-'');
if (bNeg) {
if (-ret < (INT_MIN_VALUE+digit)/) {
return INT_MIN_VALUE;
}
} else {
if (ret > (INT_MAX_VALUE-digit)/) {
return INT_MAX_VALUE;
}
} ret = *ret + digit;
} return bNeg?-ret:ret;
} //-----example-----
int main(int argc, char **argv) {
cout << "123:" << stringToInterget("") << endl;
cout << "+123:" << stringToInterget("+123") << endl;
cout << "-123:" << stringToInterget("-123") << endl;
cout << "123abc:" << stringToInterget("123abc") << endl;
cout << "abc123:" << stringToInterget("abc123") << endl;
cout << " 123:" << stringToInterget("") << endl;
cout << "123 :" << stringToInterget("123 ") << endl;
cout << "0123:" << stringToInterget("") << endl;
cout << "2147483647:" << stringToInterget("") << endl;
cout << "2147483648:" << stringToInterget("") << endl;
cout << "-2147483648:" << stringToInterget("-2147483648") << endl;
cout << "-2147483649:" << stringToInterget("-2147483649") << endl; return ;
} //-----output-----
//123:123
//+123:123
//-123:-123
//123abc:123
//abc123:0
// 123:123
//123 :123
//0123:123
//2147483647:2147483647
//2147483648:2147483647
//-2147483648:-2147483648
//-2147483649:-2147483648
9. Palindrome Number
/**********************************************************
** 9. Palindrome Number
** Determine whether an integer is a palindrome. Do this without extra space.
**********************************************************/
#include <iostream>
using namespace std; bool isPalindromeNum(int x) {
if (x < ) return false; int sourceX = x;
int reverseX = ;
int n = ;
while (x != ) {
n = x % ;
reverseX = reverseX* + n;
x /= ;
} return (sourceX == reverseX);
} //-----example-----
int main(int argc, char **argv) {
cout << "0 : " << isPalindromeNum() << endl;
cout << "121 : " << isPalindromeNum() << endl;
cout << "-121 : " << isPalindromeNum(-) << endl;
cout << "1234 : " << isPalindromeNum() << endl; return ;
} //-----output-----
//0 : 1
//121 : 1
//-121 : 0
//1234 : 0
12. Integer to Roman
/**********************************************************
** 12. Integer to Roman
** Given an integer, convert it to a roman numeral.
**
** Input is guaranteed to be within the range from 1 to 3999. ** Roman and Integer
** 1 5 10 50 100 500 1000
** I V X L C D M
**
** 1 2 3 4 5 6 7 8 9
** I II III IV V VI VII VIII IX
**
** 10 20 30 40 50 60 70 80 90
** X XX XXX XL L LX LXX LXXX XC
**
** 100 200 300 400 500 600 700 800 900
** C CC CCC CD D DC DCC DCCC CM
**********************************************************/
#include <iostream>
#include <string> using namespace std; string intToRoman(int num) {
string romanSymbol[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int intValue[] = {, , , , , , , , , , , , }; if (num < || num > ) return "-"; string result;
for (int i=; num!=; ++i) {
while (num >= intValue[i]) {
num -= intValue[i];
result += romanSymbol[i];
}
} return result;
} //-----example-----
int main(int argc, char ** argv) {
cout << "0 : " << intToRoman() << endl;
cout << "1 : " << intToRoman() << endl;
cout << "19 : " << intToRoman() << endl;
cout << "198 : " << intToRoman() << endl;
cout << "1984 : " << intToRoman() << endl;
cout << "4000 : " << intToRoman() << endl; return ;
} //-----output-----
//0 : -
//1 : I
//19 : XIX
//198 : CXCVIII
//1984 : MCMLXXXIV
//4000 : -
13. Roman to Integer
/**********************************************************
** 13. Roman to Integer
**
** Given a roman numeral, convert it to an integer.
** Input is guaranteed to be within the range from 1 to 3999.
**
** Roman and Integer
** 1 5 10 50 100 500 1000
** I V X L C D M
**
** Rule
** If a numeric symbol appears after a larger numeric symbol, use "+"
** eg: VI = V, I = 5+1 = 6 ** If a numeric symbol appears in front of a larger numeric symbol, use "-"
** eg: IX = X, I = 10-1 = 9
**********************************************************/
#include <iostream>
#include <string>
#include <map> using namespace std; int valueOfRomanChar(char ch) {
map<char, int> romanValue = {{'I',}, {'V',}, {'X',}, {'L',}, {'C',}, {'D',}, {'M',}};
return romanValue[ch];
} int romanToInteger(string s) {
if (s.size() <= ) return ; int result = valueOfRomanChar(s[]);
if (result == ) return ; for (int i=; i<s.size(); ++i) {
int prev = valueOfRomanChar(s[i-]);
int curr = valueOfRomanChar(s[i]);
if (curr == ) return ; if (prev < curr) {
result = result - prev + (curr-prev);
} else {
result += curr;
}
} return result;
} //-----example-----
int main(int argc, char **argv) {
cout << " : " << romanToInteger("") << endl;
cout << "ABC : " << romanToInteger("ABC") << endl;
cout << "MCMLXXXIV : " << romanToInteger("MCMLXXXIV") << endl;
cout << "CXCVIII : " << romanToInteger("CXCVIII") << endl;
cout << "XIX : " << romanToInteger("XIX") << endl;
cout << "I : " << romanToInteger("I") << endl; return ;
} //-----output-----
// : 0
//ABC : 0
//MCMLXXXIV : 1984
//CXCVIII : 198
//XIX : 19
//I : 1
14. Longest Common Prefix
/**********************************************************
** 14. Longest Common Prefix
** Write a function to find the longest common prefix string amongst an array of strings.
**********************************************************/
#include <iostream>
#include <string>
#include <vector> using namespace std; string longestCommonPrefix(vector<string> &strs) {
string commonPrefix = "";
if (strs.size() <= ) return commonPrefix; for (int i=; i<strs[].size(); ++i) {
string matchPrefix = strs[].substr(, i);
bool bMatch = true;
for (int j=; j<strs.size(); j++) {
if (i>strs[j].size() || matchPrefix!=strs[j].substr(,i)) {
bMatch = false;
break;
}
} if (!bMatch) {
return commonPrefix;
}
commonPrefix = matchPrefix;
} return commonPrefix;
} //-----example-----
int main(int argc, char **argv) {
vector<string> strs = {"abab", "aba", "ab"};
cout << "[\"abab\", \"aba\", \"ab\"] : " << longestCommonPrefix(strs) << endl; vector<string> strs2 = {"abab", "ba"};
cout << "[\"abab\", \"ba\"] : " << longestCommonPrefix(strs2) << endl;
return ;
} //-----output-----
//["abab", "aba", "ab"] : ab
//["abab", "ba"] :
15. 3Sum
/**********************************************************
** 15. 3Sum
** Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
**
** Note: The solution set must not contain duplicate triplets.
**
** For example, given array S = [-1, 0, 1, 2, -1, -4],
**
** A solution set is:
** [
** [-1, 0, 1],
** [-1, -1, 2]
** ]
**********************************************************/
#include <iostream>
#include <vector>
#include <algorithm> using namespace std; vector<vector<int> > threeSum(vector<int> &arrayNum) {
vector<vector<int> > result; if (arrayNum.size() < ) return result;
sort(arrayNum.begin(), arrayNum.end()); int n = arrayNum.size();
for (int i=; i<n-; ++i) {
if (i> && arrayNum[i-]==arrayNum[i]) continue; int a = arrayNum[i];
int low = i+;
int high = n-;
while (low < high) {
int b = arrayNum[low];
int c = arrayNum[high];
if (a+b+c == ) {
vector<int> v = {a, b, c};
result.push_back(v); while (low<n- && arrayNum[low]==arrayNum[low+]) ++low;
while (high> && arrayNum[high]==arrayNum[high-]) --high;
++low;
--high;
} else if (a+b+c > ){
while (high> && arrayNum[high]==arrayNum[high-]) --high;
--high;
} else {
while (low<n- && arrayNum[low]==arrayNum[low+]) ++low;
++low;
}
}
} return result;
} void printVector(vector<int> &vectorArray) {
cout << "[";
for (auto it=vectorArray.begin(); it!=vectorArray.end(); ++it) {
cout << *it;
if (it != vectorArray.end()-) cout << ", ";
}
cout << "]";
} //-----example-----
int main(int argc, char **argv) {
vector<int> arrayNum = {-, , , , -, -};
printVector(arrayNum);
cout << " : {"; vector<vector<int> > result = threeSum(arrayNum);
for (auto it=result.begin(); it!=result.end(); ++it) {
printVector(*it);
if (it != result.end()-) cout << ", ";
}
cout << "}" << endl; return ;
} //-----output-----
//[-1, 0, 1, 2, -1, -4] : {[-1, -1, 2], [-1, 0, 1]}
17. Letter Combinations of a Phone Number
/**********************************************************
** 17. 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).
**
** Input:Digit string "23"
** Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
**
** Note:
** Although the above answer is in lexicographical order, your answer could be in any order you want.
**********************************************************/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> using namespace std; vector <string> telLetterCombinations(string strDigit) {
vector<string> result;
int digitNums = strDigit.size(); if (digitNums <= ) {
result.push_back("");
return result;
} char phoneSymbols[][] = {
{' ', '_', '_', '_'}, //
{'_', '_', '_', '_'}, //
{'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'} //
}; for (int i=; i<digitNums; ++i) {
if (!isdigit(strDigit[i])) {
result.clear();
return result;
} int index = strDigit[i] - '';
if (result.size() <= ) {
for (int j=; j<&&phoneSymbols[index][j]!='_'; ++j) {
string s;
s += phoneSymbols[index][j];
result.push_back(s);
}
continue;
} vector<string> r;
for (int j=; j<result.size(); ++j) {
for (int k=; k<&&phoneSymbols[index][k]!='_'; ++k) {
string s = result[j] + phoneSymbols[index][k];
r.push_back(s);
}
}
result = r;
} return result;
} void printVector(vector<string> &s) {
cout << "[";
for (auto it=s.begin(); it!=s.end(); ++it) {
cout << *it;
if (it != s.end()-) cout << ", ";
}
cout << "]" << endl;
} int main(int argc, char **argv) {
vector<string> str23 = telLetterCombinations("");
cout << "23 : ";
printVector(str23); vector<string> str1 = telLetterCombinations("");
cout << "1 : ";
printVector(str1); vector<string> str3a = telLetterCombinations("3a");
cout << "3a : ";
printVector(str3a); vector<string> str203 = telLetterCombinations("");
cout << "203 : ";
printVector(str203); return ;
} //-----output-----
//23 : [ad, ae, af, bd, be, bf, cd, ce, cf]
//1 : []
//3a : []
//203 : [a d, a e, a f, b d, b e, b f, c d, c e, c f]
19. Remove Nth Node From End of List
/**********************************************************
** 19. 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.
**
** Note:
** Given n will always be valid.
** Try to do this in one pass.
**********************************************************/
#include <iostream>
#include <vector> using namespace std; struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
}; ListNode *removeNthNodeOfEnd(ListNode *head, int n) {
if (head==nullptr || n<=) return nullptr; ListNode fakeHead();
fakeHead.next = head;
head = &fakeHead; ListNode *p1 = head;
ListNode *p2 = head;
for (int i=; i<n; ++i) {
if (p2 == nullptr) return nullptr;
p2 = p2->next;
} while (p2->next != nullptr) {
p2 = p2->next;
p1 = p1->next;
} p1->next = p1->next->next; return head->next;
} ListNode *createListNode(vector<int> valVector) {
ListNode *head = nullptr;
ListNode *p = nullptr; for (auto it=valVector.begin(); it!=valVector.end(); ++it) {
if (head == nullptr) {
p = new ListNode(*it);
head = p;
} else {
p->next = new ListNode(*it);
p = p->next;
}
} return head;
} void printListNode(ListNode *pListNode) {
while (pListNode != nullptr) {
cout << pListNode->val;
if (pListNode->next != nullptr) cout << "->";
pListNode = pListNode->next;
}
} //-----example-----
int main(int argc, char **argv) {
vector<int> arrayList = {,,,,};
ListNode *pList = createListNode(arrayList);
printListNode(pList);
cout << ", n=2" <<endl; ListNode *pRemoveList = removeNthNodeOfEnd(pList, );
printListNode(pRemoveList);
cout << endl; return ;
} //-----output-----
//1->2->3->4->5, n=2
//1->2->3->5
20. Valid Parentheses
/**********************************************************
** 20. 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.
**********************************************************/
#include <iostream>
#include <string>
#include <stack> using namespace std; bool isValidParentheses(string s) {
if (s.size() <= ) return true; stack<char> stackCh;
for (auto ch : s) {
if (ch=='(' || ch=='{' || ch=='[') {
stackCh.push(ch);
} else if (ch==')' || ch=='}' || ch==']') {
if (stackCh.empty()) return false; char sch = stackCh.top();
if ((ch==')' && sch=='(') || (ch=='}' && sch=='{') || (ch==']' && sch=='[')) {
stackCh.pop();
} else {
return false;
}
} else {
return false;
}
} return stackCh.empty();
} //-----example-----
int main(int argc, char **argv) {
cout << "\"\" : " << isValidParentheses("") << endl;
cout << "\"()\" : " << isValidParentheses("()") << endl;
cout << "\"()[]{}\" : " << isValidParentheses("()[]{}") << endl;
cout << "\"([)]\" : " << isValidParentheses("([)]") << endl; return ;
} //-----output-----
//"" : 1
//"()" : 1
//"()[]{}" : 1
//"([)]" : 0
22. Generate Parentheses
/**********************************************************
** 22. Generate Parentheses
** Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
**
** For example, given n = 3, a solution set is:
**
** [
** "((()))",
** "(()())",
** "(())()",
** "()(())",
** "()()()"
** ]
**********************************************************/
#include <iostream>
#include <vector>
#include <string> using namespace std; void generatorSubParentheses(vector<string> &result, int left, int right, string s) {
if (left== && right==) {
result.push_back(s);
return;
} if (left > ) {
generatorSubParentheses(result, left-, right, s+'(');
} if (right> && right>left) {
generatorSubParentheses(result, left, right-, s+')');
}
} vector<string> generatorParentheses(int n) {
vector<string> result;
string s;
generatorSubParentheses(result, n, n, s); return result;
} void printVector(vector<string> &result) {
for (int i=; i<result.size(); ++i) {
cout << " \"" <<result[i] << "\"";
if (i != result.size()-) cout << ",";
cout << endl;
}
} //-----example-----
int main(int argc, char **argv) {
vector<string> result = generatorParentheses();
cout << "3 parentheses:" << endl;
cout <<"[" << endl;
printVector(result);
cout << "]" << endl; return ;
} //-----output-----
//3 parentheses:
//[
// "((()))",
// "(()())",
// "(())()",
// "()(())",
// "()()()"
//]
24. Swap Nodes in Pairs
/**********************************************************
** 24. Swap Nodes in Pairs
** Given a linked list, swap every two adjacent nodes and return its head.
**
** For example,
** Given 1->2->3->4, you should return the list as 2->1->4->3.
**
** Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
**********************************************************/
#include <iostream>
#include <vector> using namespace std; struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
}; ListNode *swapPairsNodes(ListNode *head) {
for (auto p=head; p!=nullptr&&p->next!=nullptr; p=p->next->next) {
int tempVal = p->val;
p->val = p->next->val;
p->next->val = tempVal;
} return head;
} ListNode *createListNode(vector<int> vectorVal) {
ListNode *head = nullptr;
ListNode *p = nullptr; for (auto it=vectorVal.begin(); it!=vectorVal.end(); ++it) {
if (head == nullptr) {
p = new ListNode(*it);
head = p;
} else {
p->next = new ListNode(*it);
p = p->next;
}
} return head;
} void printListNode(ListNode *pListNode) {
while (pListNode != nullptr) {
cout << pListNode->val;
if (pListNode->next != nullptr) cout << "->";
pListNode = pListNode->next;
}
} //-----example-----
int main(int argc, char **argv) {
vector<int> listVector = {,,,};
ListNode *sourceListNode = createListNode(listVector);
printListNode(sourceListNode);
cout << endl << "swap nodes in pairs:" << endl; ListNode *destListNode = swapPairsNodes(sourceListNode);
printListNode(destListNode);
cout << endl; return ;
} //-----output-----
//1->2->3->4
//swap nodes in pairs:
//2->1->4->3
26. Remove Duplicates from Sorted Array
/**********************************************************
** 26. Remove Duplicates from Sorted Array
** Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
**
** Do not allocate extra space for another array, you must do this in place with constant memory.
**
** For example,
** Given input array nums = [1,1,2],
**
** Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
**********************************************************/
#include <iostream> using namespace std; int removeDuplicatesSortedArray(int A[], int n) {
if (n <= ) return n; int index = ;
for (int i=; i<n-; ++i) {
if (A[i] != A[i+]) {
A[++index] = A[i+];
}
} return index+;
} //-----example-----
int main(int argc, char **argv) {
int A[] = {, , };
int n = sizeof(A)/sizeof(int); cout << "Given array :[";
for (int i=; i<n; ++i) {
cout << A[i];
if (i != n-) cout << ",";
}
cout << "]" << endl; int len = removeDuplicatesSortedArray(A,n);
cout << "length = " << len << endl;
cout << "Dest array :[";
for (int i=; i<len; ++i) {
cout << A[i];
if (i != len-) cout << ",";
}
cout << "]" << endl; return ;
} //-----output-----
//Given array :[1,1,2]
//length = 2
//Dest array :[1,2]
27. Remove Element
/**********************************************************
** 27. Remove Element
** Given an array and a value, remove all instances of that value in place and return the new length.
**
** Do not allocate extra space for another array, you must do this in place with constant memory.
**
** The order of elements can be changed. It doesn't matter what you leave beyond the new length.
**
** Example:
** Given input array nums = [3,2,2,3], val = 3
**
** Your function should return length = 2, with the first two elements of nums being 2.
**********************************************************/
#include <iostream>
#include <vector> using namespace std; int removeElement(vector<int> &array, int val) {
int length = ;
int arraySize = array.size(); if (arraySize <= ) return length; for (int i=; i<arraySize; ++i) {
if (array[i] != val) {
array[length++] = array[i];
}
} array.resize(length); return length;
} void printVector(vector<int> &array) {
cout << "[";
for (int i=; i<array.size(); ++i) {
cout << array[i];
if (i != array.size()-) cout << ",";
}
cout << "]";
} //-----example-----
int main(int argc, char **argv) {
vector<int> array = {,,,};
cout << "Source array:";
printVector(array);
cout << endl; cout << "Remove element val=3, then length = " << removeElement(array, ) << endl; cout << "Dest array:";
printVector(array);
cout << endl; return ;
} //-----output-----
//Source array:[3,2,2,3]
//Remove element val=3, then length = 2
//Dest array:[2,2]
28. Implement strStr()
/**********************************************************
** 28. Implement strStr()
**
** Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
**********************************************************/
#include <iostream>
#include <string> using namespace std; int strStr(string haystack, string needle) {
int lenH = haystack.size();
int lenN = needle.size(); if (lenH<= || lenN<= || lenN>lenH) return -; int indexH = ;
int indexN = ;
while (indexH<lenH && indexN<lenN) {
if (indexN >= lenN) break; if (haystack[indexH] == needle[indexN]) {
++indexN;
} else {
indexN = ;
}
++indexH;
} if (indexN >= lenN) return (indexH-lenN); return -;
} //-----example-----
int main(int argc, char **argv) {
cout << "\"hello world\", \"\" : " << strStr("hello world", "") << endl;
cout << "\"\", \"world\" : " << strStr("", "world") << endl;
cout << "\"hello world\", \"world\" : " << strStr("hello world", "world") << endl;
cout << "\"hello world\", \"word\" : " << strStr("hello world", "word") << endl; return ;
} //-----output-----
//"hello world", "" : -1
//"", "world" : -1
//"hello world", "world" : 6
//"hello world", "word" : -1
31. Next Permutation
/**********************************************************
** 31. Next Permutation
** Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
**
** If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
**
** The replacement must be in-place, do not allocate extra memory.
**
** Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
** 1,2,3 → 1,3,2
** 3,2,1 → 1,2,3
** 1,1,5 → 1,5,1
**
** ---------------------------------------
** The pattern can be descripted as below:
**
** 1) from n-1 to 0, find the first place [i-1] which num[i-1] < num[i]
** 2) from n-1 to i, find the first number from n-1 to i which >= num[i-1]
** 3) swap the 2) num with the num[i-1]
** 4) sort the sub-array [i, n) //actuall sort is fine as well
**
** For example:
**
** 1 4 3 2 <-- 1) find the first place which num[i-1] < num[i]
** ^
**
** 1 4 3 2 <-- 2) find the first number from n-1 to i which >= num[i-1]
** ^ ^
**
** 2 4 3 1 <-- 3) swap them
** ^ ^
**
** 2 4 3 1 <-- 4) sort
** ^ ^
**
** 2 1 3 4
**
** Edge Case:
**
** 4 3 2 1, the next permutation is 1 2 3 4
**********************************************************/
#include <iostream>
#include <vector>
#include <algorithm> using namespace std; void nextPermutation(vector<int> &num) {
if (num.size() <= ) return; for (int i=num.size()-; i>; --i) {
if (num[i-] < num[i]) {
int j = num.size()-;
while (num[i-] > num[j]) --j; int tmp = num[j];
num[j] = num[i-];
num[i-] = tmp; sort(num.begin()+i, num.end());
return;
} if (i == ) {
sort(num.begin(), num.end());
return;
}
}
} void printVector(vector<int> &num) {
for (auto it=num.begin(); it!=num.end(); ++it) {
cout << *it;
if (it != num.end()-) cout << ",";
}
} void testVector(vector<int> &num) {
printVector(num);
cout << " -> ";
nextPermutation(num);
printVector(num);
cout << endl;
} //-----example-----
int main(int argc, char **argv) {
vector<int> num = {,,};
testVector(num); num = {,,};
testVector(num); num = {,,};
testVector(num); num = {,,,};
testVector(num); num = {,,,};
testVector(num); return ;
} //-----output-----
//1,2,3 -> 1,3,2
//3,2,1 -> 1,2,3
//1,1,5 -> 1,5,1
//1,4,3,2 -> 2,1,3,4
//4,3,2,1 -> 1,2,3,4
32. Longest Valid Parentheses
/**********************************************************
** 32. Longest Valid Parentheses
** Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
**
** For "(()", the longest valid parentheses substring is "()", which has length = 2.
**
** Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
**********************************************************/ #include <iostream>
#include <vector>
#include <string> using namespace std; int longestValidParentheses(string s, string &subs) {
if (s.size() <= ) return ; int longestLen = ;
int lastErrPos = -;
int matchPos = -;
vector<int> matchStack; for (int i=; i<s.size(); ++i) {
if (s[i] == '(') {
matchStack.push_back(i);
} else if (s[i] == ')') {
if (matchStack.size() > ) {
matchStack.pop_back();
int len;
if (matchStack.size() == ) {
len = i - lastErrPos;
matchPos = lastErrPos + ;
} else {
len = i - matchStack.back();
matchPos = matchStack.back() + ;
} if (len > longestLen) {
longestLen = len;
subs = s.substr(matchPos, longestLen);
}
} else {
lastErrPos = i;
}
} } return longestLen;
} void testFun(string s, string &subs) {
cout << "string : " << s << endl;
cout << "length : " << longestValidParentheses(s, subs) << endl;
cout << "substring: " << subs << endl;
cout << "------------------------" << endl;
} //-----example-----
int main(int argc, char **argv) {
string subs; string s = "(()";
testFun(s, subs); s = ")()())";
testFun(s, subs); s = "()((())))()";
testFun(s, subs); return ;
} //-----output-----
//string : (()
//length : 2
//substring: ()
//------------------------
//string : )()())
//length : 4
//substring: ()()
//------------------------
//string : ()((())))()
//length : 8
//substring: ()((()))
//------------------------
34. Search for a Range
/**********************************************************
** 34. Search for a Range
** Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
**
** Your algorithm's runtime complexity must be in the order of O(log n).
**
** If the target is not found in the array, return [-1, -1].
**
** For example,
** Given [5, 7, 7, 8, 8, 10] and target value 8,
** return [3, 4].
**********************************************************/
#include <iostream>
#include <vector> using namespace std; int binarySearch(vector<int> array, int low, int high, int key) {
while (low <= high) {
int mid = low + (high - low) / ;
if (array[mid] == key) {
return mid;
} if (key > array[mid]) {
low = mid + ;
} if (key < array[mid]) {
high = mid - ;
}
} return -;
} vector<int> searchRange(vector<int> array, int target) {
vector<int> result; int nums = array.size();
if (nums <= ) {
result = {-, -};
} int pos = binarySearch(array, , nums-, target);
int low = -;
int high = -; if (pos >= ) {
low = pos;
high = pos; int lowPos = low;
do {
low = lowPos;
lowPos = binarySearch(array, , low-, target);
} while(lowPos >= ); int highPos = high;
do {
high = highPos;
highPos = binarySearch(array, high+, nums-, target);
} while (highPos >= );
} result.push_back(low);
result.push_back(high); return result;
} void printVector(vector<int> array) {
cout << "[";
for (int i=; i<array.size(); ++i) {
cout << array[i];
if (i != array.size()-) cout << ",";
}
cout << "]";
} //-----example-----
int main(int argc, char **argv) {
vector<int> array = {,,,,,};
int target = ; vector<int> result = searchRange(array, target);
printVector(array);
cout << ", target:" << target << " then result:";
printVector(result);
cout << endl; target = ;
result = searchRange(array, target);
printVector(array);
cout << ", target:" << target << " then result:";
printVector(result);
cout << endl; array = {,,,,,};
target = ;
result = searchRange(array, target);
printVector(array);
cout << ", target:" << target << " then result:";
printVector(result);
cout << endl; return ;
} //-----output-----
//[5,7,7,8,8,10], target:8 then result:[3,4]
//[5,7,7,8,8,10], target:9 then result:[-1,-1]
//[8,8,8,8,8,8], target:8 then result:[0,5]
35. Search Insert Position
/**********************************************************
** 35. Search Insert Position
** Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
**
** You may assume no duplicates in the array.
**
** Here are few examples.
** [1,3,5,6], 5 → 2
** [1,3,5,6], 2 → 1
** [1,3,5,6], 7 → 4
** [1,3,5,6], 0 → 0
**********************************************************/
#include <iostream>
#include <vector> using namespace std; int searchInsertPos(vector<int> array, int target) {
int nums = array.size();
if (nums <= ) return ; for (int i=; i<nums; ++i) {
if (array[i] >= target) {
return i;
}
} return nums;
} //-----example-----
int main(int argc, char **argv) {
vector<int> array = {,,,};
cout << "[1,3,5,6], 5 -> " << searchInsertPos(array, ) << endl;
cout << "[1,3,5,6], 2 -> " << searchInsertPos(array, ) << endl;
cout << "[1,3,5,6], 7 -> " << searchInsertPos(array, ) << endl;
cout << "[1,3,5,6], 0 -> " << searchInsertPos(array, ) << endl; return ;
} //-----output-----
//[1,3,5,6], 5 -> 2
//[1,3,5,6], 2 -> 1
//[1,3,5,6], 7 -> 4
//[1,3,5,6], 0 -> 0
LeetCode Algorithm的更多相关文章
- LeetCode Algorithm 05_Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...
- LeetCode Algorithm 133_Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- LeetCode Algorithm 07_Reverse Integer
Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to ...
- LeetCode Algorithm 06_ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- LeetCode Algorithm 04_Median of Two Sorted Arrays
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted ...
- LeetCode Algorithm 03_Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, ...
- LeetCode Algorithm 02_Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- LeetCode Algorithm 01_Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- Leetcode study time
August 2, 2015 在http://zzk.cnblogs.com/ 用"找一找", 花了几个小时, 找出比较好的Leetcode博客. Read the leetcod ...
随机推荐
- 第一章:pip 安装 和 卸载 django
1. 在dos命令行中输入 pip 如下命令进行安装: 安装最新的版本的 Django 命令如下: pip install django 安装 指定版本的 Django 命令如下: pip insta ...
- TCP长连接与短连接的原理及区别
一.当网络通信时采用TCP协议时: 1.过程: 第一步:(在真正的读写操作之前)Server 和Client 之间必须建立一个连接,连接的建立需要三次握手 经典的三次握手示意图: 第二步:进行读写操 ...
- Win环境下Oracle小数据量数据库的物理备份
Win环境下Oracle小数据量数据库的物理备份 环境:Windows + Oracle 单实例 数据量:小于20G 重点:需要规划好备份的路径,建议备份文件和数据库文件分别存在不同的存储上. 1.开 ...
- windows安装程序无法将windows配置为在此计算机的硬件上运行
关于装windows系统时,出现一些安装中断的处理 该方法适用于 windows安装程序无法将windows配置为在此计算机的硬件上运行 计算机意外地重新启动或遇到错误. Windows 安装无法继续 ...
- 自制权限框架(一)jsp标签
一.概述 在我们的系统中,很多时候都用到了权限.最简单的权限就是登录.登录了,我就可以自己的相关信息:没有登录,就不能看到. 目前比较流行的权限框架就是apache shiro和spring secu ...
- CJOJ 2482 【POI2000】促销活动
CJOJ 2482 [POI2000]促销活动(STL优先队列,大根堆,小根堆) Description 促销活动遵守以下规则: 一个消费者 -- 想参加促销活动的消费者,在账单下记下他自己所付的费用 ...
- curl学习之curl_setopt参数设置大总结
CURL函数库里最重要的函数是curl_setopt(),它可以通过设定CURL函数库定义的选项来定制HTTP请求使用方法:bool curl_setopt (int ch, string optio ...
- 使用 electron 实现类似新版 QQ 的登录界面效果(阴影、背景动画、窗体3D翻转)
上文<使用 VS2017 和 js 进行桌面程序开发 - electron 之 Hello Word>介绍了如何使用 VS2017 开发 electron 桌面程序,今天来点有看头的,但是 ...
- js模块加载之AMD和CMD
当我写这篇文章的时候,sea.js已经逐渐退出历史的舞台,详细链接.不过任何新事物的出现都是对旧事物的取其精华,去其糟粕,所以了解一下以前模块的加载也是一件好事. js模块化的原因自不比多说,看看HU ...
- xdu_1077:循环节长度
题意很简单,就是给出p,q,求p/q的循环节长度. 由循环小数的循环部分的值等于等比数列求和的值S,列公式得到最简分数分母的值.最终得10^x%q==1(其中q为经过modify之后的值).搞清这些之 ...