1.TwoSum
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].
solution
想到用map<int,int>来实现 first为数值,second为索引
对数组进行循环,每次查找map中是否有target - nums[i]数字存在。如果有返回索引
否则把当前数字加入map,继续循环。
时间复杂度为O{n},(这里留一个坑 如果map的find算法的时间复杂是O(1)的话)
感觉还是需要把STL源码剖析看一下,不然对map这些底层的实现效率都不是很了解
2.Add Twonum
u 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.
首先这道题有可能一个数字为0 或者出现进位的情况
大题思路是:对两个链表进行循环,直到其中一个到尾。每次记录进位标志,以及清零标志。
下次计算高位时选择+1/不加。
注意 corner case:5+5 循环只循环一次 但是有进位出现,所以循环结束后还需处理进位符号
注意 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.
找最大不重复子串,思路是:对字符串进行遍历,把每个字符串都放入一个vector<int>中
提前创建256个空间 初始化为-1
因为每一个字母都是一个asiical码,可以把每个索引都放入字母Asiical对应的位置
记录最大不重复子串的开始位置。当 当前循环的字母所在位置上已经有字母时,更新起始位置为重复的字母的索引
更新最大子串长度
代码实现如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};
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
对两个已经排序的数组,寻找其中位数
第一个想到的算法就是对其进行归并排序,然后直接取数字。
看到网上还有一个简单的算法是用二分法
可以参考
https://www.cnblogs.com/ganganloveu/p/4180523.html
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"
回文算法,暴力算法:直接遍历,然后向两边展开,看是不是回文,不过要分奇偶情况
还有一种简单算法,马拉车算法 可以参考