leetcode.com
\1. Two Sum
Easy
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].
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result(2,0);
for(int i=0;i<nums.size()-1;++i){
for(int j=i+1;j<nums.size();++j){
if(nums[i]+nums[j] == target){
result[0] = i ;
result[1] = j ;
return result;
}
}
}
return result;
}
};
簡單的雙層循環
\2. Add Two Numbers
Medium
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *h = new ListNode(0);
ListNode *p = h;
int temp = 0;//remeber the value of step next.
while(l1 &&l2 ){
p->next = new ListNode((l2->val + l1->val + temp)% 10 );// must be single digit
temp = (l2->val + l1->val + temp) /10;
p = p->next;
l1 = l1->next;
l2 = l2->next;
}
//if l1 is not end
while(l1){
p->next = new ListNode((l1->val + temp)% 10 );// must be single digit
temp = ( l1->val + temp) /10;
p = p->next;
l1 = l1->next;
}
//if l2 not end
while(l2){
p->next = new ListNode((l2->val + temp)% 10 );// must be single digit
temp = ( l2->val + temp) /10;
p = p->next;
l2= l2->next;
}
if(temp!=0)
p->next = new ListNode(1);
return h->next; //return the next node of LlistHead
}
};
\3. Longest Substring Without Repeating Characters
Medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int p1=0,p2=0,maxlen=0;
int len = s.size();
int book[256] = {0}; //record if the character exist
while(p2<len){
if(book[s[p2]]==1){//detect repeat char,update book and move p1
maxlen = max(maxlen, p2 - p1);
while(s[p1]!=s[p2]){// move p1 to the same char
book[s[p1]] = 0;//set to zero
p1++;
}
p1++;//move p1 to next unick char
}
else{// p2 char is not repeated
book[s[p2]] = 1;
}
p2++;//move p2
}
maxlen = max(maxlen, p2-p1);// dont forget, when input is " ", lenght==1
return maxlen;
}
};
\4. Median of Two Sorted Arrays
Hard
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int mid_len = (int)(len1+len2) /2+1;
//create an array to store the values of half of nums1 and nums2.
float store[mid_len] = {0};
int k =0;
int i=0,j=0;
while(i<len1&&j<len2&&k<mid_len){
if(nums1[i]<=nums2[j]){
store[k++] = nums1[i++];
}
else if(nums2[j]<=nums1[i]){
store[k++] = nums2[j++];
}
}
while(i<len1&&k<mid_len){
store[k++] = nums1[i++];
}
while(j<len2&&k<mid_len){
store[k++] = nums2[j++];
}
if((len1+len2)%2==1)// ji shu
return store[mid_len-1];
else
return (store[mid_len-1]+store[mid_len-2]) /2;
}
};
Success
Details
Runtime: 16 ms, faster than 99.04% of C++ online submissions for Median of Two Sorted Arrays.
Memory Usage: 9.7 MB, less than 99.28% of C++ online submissions for Median of Two Sorted Arrays.
\5. Longest Palindromic Substring
Medium
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
找最大回文字符串
思路 初始化一個只有一個字符的result字符串。 遍歷string s 的每一個位置(除了最後一個位置), 考慮兩種情況:
- 迴文是 偶數個字符
- 迴文是奇數個字符
全部調用一個twoside
函數,截取以 i
爲中心的最長迴文string
, 每次事後都比較一下是否要更新最長結果string result
。
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length();
if(len==0)// dont forgetit
return "";
string result = s.substr(0,1);
for(int i=0;i<len-1;i++){// consider palindromic substring 是偶數個字符, so <len-1
string newsubstr = twoside(s,i,i);//奇數個字符的palindromic substring
if(result.length() < newsubstr.length())
result = newsubstr;
string newsubstr = twoside(s,i,i+1);//偶數個字符
if(result.length() < newsubstr.length())
result = newsubstr;
}
return result;
}
string twoside(string s, int left, int right){
while(left>=0&&right<=s.length()-1&&s[left]==s[right]){
left++;right--;
}
return s.substr(left+1,right-(left+1));
}
};
Success
Details
Runtime: 36 ms, faster than 60.90% of C++ online submissions for Longest Palindromic Substring.
Memory Usage: 119.6 MB, less than 17.78% of C++ online submissions for Longest Palindromic Substring.
TAG
可以有更好的解法
\6. ZigZag Conversion
Medium
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
思路 while
循環整個字符串, 在循環中分兩個for
循環,第一個存儲 豎 直列的字符(比如PAYP)到存了 n行字符串的nstring
中,對應“行”存到對應的字符串nstring[i]
。 第二個for
存儲 斜對角的字符到對應字符串nstring
中。
最後, 按順序轉化輸出就行啦!
class Solution {
public:
string convert(string s, int numRows) {
string output;
string nstring[numRows];
int i=0;
while(i<s.length()){
//generate the column chars
for(int jj=0;jj<numRows&&i<s.length();)
nstring[jj++] += s[i++];
//generate the 斜對角 chars, not contains the first row and last row
for(int kk=numRows-2;kk>0&&i<s.length();)//the start idx of kk is numRows-2
nstring[kk--] += s[i++];
}
// push into the output String
for(int rowi=0;rowi<numRows;rowi++)
output += nstring[rowi];
return output;
}
};
\7. Reverse Integer
Easy
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
注意處理overflow問題
class Solution {
public:
int reverse(int x) {
string s = to_string(x);
if(s[0] == '-')
std::reverse(s.begin()+1,s.end());
else
std::reverse(s.begin(),s.end());
long long out = stoll(s);
if(out <-2147483648 || out >2147483647)
out =0;
return (int)out;
}
};