您的位置:首页 > 其它

Leetcode 刷题计划

2016-02-26 16:16 232 查看

Two Sum 21.4% Medium


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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.


给定一个数组,找到数组中的两个值,使其和为n,假定数组中一定存在这样一组解。

常规的思路是两次循环,如果了解哈希表的话,我们可以用哈希表来记录遍历过的节点,找到当前节点和(n-i)节点所在的位置即可。这样可以在O(n)的时间复杂度里面解决这个问题。

Add Two Numbers 22.3% Medium


You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


大数字的加法,把两个数字都表示成链表的形式。

Longest Substring Without Repeating Characters 21.6% Medium


Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


由于是字符串,这样的话递归或者多次循环都会导致超时。技巧还是用hash的方法来记录遍历过的字符,另外一个就是如何减少遍历个数。

Median of Two Sorted Arrays 18.2% 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)).


从两个已经排序的数组a[m],b
中找到中间的数,如果m+n为偶数,则返回中间两个数的平均值,要求时间复杂度log(m+n)

如果写一个时间复杂度是o(m+n)/2 的方法,思路上就简单了,只需要实现即可。既然要求时间复杂度是log(m+n),意味着需要二分法。这道题可以转换成求第k大元素所在的位置,假设第k大元素在a[m]中的index为x,那么b
中的索引为k-x,我们通过二分法找x所在的位置,满足 a[x],b[k-x]中较大的一个元素同时小于a[x+1],b[k-x+1]即可。

Longest Palindromic Substring 22.6% Medium


Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


回文可以理解成对称子串,如aaaa,abc,abba,abcba都是回文,由于此题中假设了前提字符串长度不超过1000,那就意味着我们可以使用递归,不会出现堆栈溢出的情况。每一个回文都一定有一个中轴,因此找最长回文就转化为找中轴的问题,如果回文长度为奇数,中轴为1个元素,回文长度为偶数中轴为2个元素。寻找中轴需要一次循环,每一个中轴寻找对称字符串大概小于2n,因此时间复杂度为 n^2.

有人说更牛逼的解法是后缀树,目前还没有找到相关的材料。

上述问题的参考代码:

https://github.com/cuicheng11165/myleetcode/tree/master/leetcode/leetcode
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: