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].
class Solution { public: vectortwoSum(vector & nums, int target) { unordered_map num_index_dict; vector res; for (int i = 0; i < nums.size(); i++) { if (num_index_dict.find(nums[i]) != num_index_dict.end()) { int index = num_index_dict[nums[i]]; res.push_back(index); res.push_back(i); return res; } else { num_index_dict[target - nums[i]] = i; } } return res; } };
2. Add Two Numbers
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) { int carry = 0; ListNode* dummy_head = new ListNode(0); ListNode* head = dummy_head; while (l1 || l2 || carry) { int temp = carry; if (l1) { temp += l1 -> val; l1 = l1 -> next; } if (l2) { temp += l2 -> val; l2 = l2 -> next; } carry = temp / 10; int cur_val = temp % 10; head -> next = new ListNode(cur_val); head = head -> next; } return dummy_head -> next; } };
3. Longest Substring Without Repeating Characters
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) { if (s.empty()) { return 0; } int left = 0; int right = 0; int pos_dict[128]; for (int i = 0; i < 128; i++) { pos_dict[i] = -1; } int res = 0; while (right < s.size()) { char cur_char = s[right]; if (pos_dict[(int)cur_char] == -1) { pos_dict[(int)cur_char] = right; right += 1; } else { res = max(res, right - left); int last_index = pos_dict[(int)cur_char]; // 注意此处 for (int i = left; i<= last_index; i++) { pos_dict[(int)s[i]] = -1; } left = last_index + 1; pos_dict[(int)cur_char] = right; right += 1; } } res = max(res, right - left); return res; } };
class Solution { public: int lengthOfLongestSubstring(string s) { if (s.empty()) { return 0; } int left = 0; int right = 0; int pos_dict[128]; for (int i = 0; i < 128; i++) { pos_dict[i] = -1; } int res = 0; while (right < s.size()) { char cur_char = s[right]; if (pos_dict[(int)cur_char] == -1) { pos_dict[(int)cur_char] = right; right += 1; } else { res = max(res, right - left); int last_index = pos_dict[(int)cur_char]; // 注意此处 left = max(left, last_index + 1); pos_dict[(int)cur_char] = right; right += 1; } } res = max(res, right - left); return res; } };
4. Median of Two Sorted Arrays
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& nums1, vector & nums2) { if (nums1.empty() && nums2.empty()) { return 0; } int total_size = nums1.size() + nums2.size(); vector ::iterator iter1 = nums1.begin(); vector ::iterator iter2 = nums2.begin(); int num = 0; int lower; int upper; while (num < (total_size + 1) / 2) { if (iter1 == nums1.end()) { lower = *iter2++; } else if (iter2 == nums2.end()) { lower = *iter1++; } else { lower = (*iter1 < *iter2) ? *iter1++ : *iter2++; } num++; } if (total_size % 2 == 1) { return lower; } if (iter1 == nums1.end()) { upper = *iter2; } else if (iter2 == nums2.end()) { upper = *iter1; } else { upper = (*iter1 < *iter2) ? *iter1 : *iter2; } return (lower + upper) / 2.0; } };
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 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
class Solution { public: string longestPalindrome(string s) { if (s.size() < 2) { return s; } int arr[2] = {0, 0}; for (int i = 0; i < s.size() - 1; i++) { longestPalindromeHelper(s, i, i, arr); longestPalindromeHelper(s, i, i + 1, arr); } return s.substr(arr[0], arr[1]); } void longestPalindromeHelper(string s, int i, int j, int arr[]) { while (i >= 0 && j < s.size() && s[i] == s[j]) { i--; j++; } if (j - i - 1 > arr[1]) { arr[1] = j - i - 1; arr[0] = i + 1; } } };
class Solution { public: string longestPalindrome(string s) { if (s.size() < 2) { return s; } int start = 0; int max_length = 1; bool dp[s.size()][s.size()] = {false}; for (int d = 1; d < s.size(); d++) { // 注意此处 for (int i = 0; i + d < s.size(); i++) { int j = i + d; if (s[i] == s[j] && (d <= 2 || dp[i + 1][j - 1])) { dp[i][j] = true; if (d + 1 > max_length) { max_length = d + 1; start = i; } } } } return s.substr(start, max_length); } };
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 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
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) { return s; } vectorrows(min(int(s.size()), numRows)); int curRow = 0; bool going_down = false; for (char c : s) { rows[curRow] += c; if (curRow == 0 || curRow == numRows - 1) { going_down = !going_down; } curRow = going_down ? curRow + 1 : curRow - 1; } string res; for (string str : rows) { res += str; } return res; } };
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) { return s; } string res = ""; int cycle_length = 2 * numRows - 2; for (int i = 0; i < numRows; i++) { for (int j = 0; j + i < s.size(); j += cycle_length) { res += s[j + i]; if (i != 0 && i != numRows - 1 && j + cycle_length - i < s.size()) { res += s[j + cycle_length - i]; } } } return res; } };