Tag Archiv: leetcode

Leetcode 295. Find Median from Data Stream

题目链接295. Find Median from Data Stream

  在一个有序数组中找中位数,但需要支持再数组中添加新的元素。本来是有序里的,可以很轻易就查到中位数,但如果添加新数字后,不一定有序。如果先对数组排序,那代价就比较大了,每次排序时间复杂度O(n*log(n)),看discuss发现了一种很巧妙的解法,可以把添加数据的时间复杂度降低到O(log(n)) ,查询中位数O(1)。
(more…)

Leetcode 19.Remove Nth Node From End of List

题目链接:19. Remove Nth Node From End of List

  删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
(more…)

Leetcode 114. Flatten Binary Tree to Linked List

Leetcode 114. Flatten Binary Tree to Linked List

  题目意思很简单,就是把一棵二叉数转换为链表,虽然题目中没说以什么样的形式转换,但看下样例就很容易看出来,是以先序遍历的次序转换成链表。这里链表节点还是treenode,只不过它的左节点为空而已。
(more…)

Leetcode 467. Unique Substrings in Wraparound String

题目链接:Unique Substrings in Wraparound String
这里加段英文,不是为了凑字数,而是为了让别人搜索题目的时候能搜到我的博客。。
Consider the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s will look like this: “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.
(more…)

Leetcode 368. Largest Divisible Subset

题目链接:368. Largest Divisible Subset

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
  题目意思也很简单,给出一个不含重复数字的数组,找到最长的一个子数组,子数组里的元素必须两两整除。
(more…)

Leetcode 53. Maximum Subarray

题目链接:53.Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray [4,−1,2,1] has the largest sum = 6.
  题意简单,给出一个数组,求出其中最大的子数组和。

(more…)

Leetcode 372. Super Pow

题目链接:Super Pow

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
  简短的题目,让你求(a^b)%1337的值,但b是以数组的形式给出的,这就意味着b可能非常非常大。看到题目我立马想到了大数的快速幂取模,利用java自带的Biginteger应该可以很轻易做的,但仔细想想,其实java做做大数的运算非常慢的,虽然代码简单了,但实际上是让计算机去做大量的计算,所以我就放弃了这种想法,不知道直接大数快速幂取模能不能ac。

(more…)

Leetcode 240. Search a 2D Matrix II

题目链接:Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.

  此题是74题Search a 2D Matrix的升级版,所给出的矩阵性质相对74题少了一条,只保证了每行和每列都是增序的,但依旧有O(m+n)的解法。

(more…)

Leetcode 74. Search a 2D Matrix

题目链接:Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
* Integers in each row are sorted from left to right.
* The first integer of each row is greater than the last integer of the previous row.

  这道题很简单,为此专门写篇博客其实算博客凑数了。给你一个每一行每一列都是增序,且每一行第一个数都大于上一行末尾数的矩阵,让你判断某个数在这个矩阵中是否存在。

(more…)