Zhuanli&Blog


  • 首页

  • 标签

  • 分类

  • 归档

leetcode 386. Lexicographical Numbers

发表于 2018-05-31 | 分类于 leetcode

Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.

  • my solution

    1
    return sorted([i for i in range(1,n+1)],key=str)
  • a clear solution:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    def order(n):
    out = []
    cur = 1
    for i in range(1,n+1):
    out.append(cur)
    if cur*10 <= n:
    cur *= 10
    elif cur%10 != 9 and cur + 1 <= n:
    cur += 1
    else:
    while (cur//10)%10 == 9:
    cur = cur//10
    cur = cur//10 + 1
    return out

leetcode 388. Longest Absolute File Path

发表于 2018-05-30 | 分类于 leetcode

Suppose we abstract our file system by a string in the following manner:

The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:


dir
subdir1
subdir2
file.ext

The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.

The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:


dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext

The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.

We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).

Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.

Note:

  • The name of a file contains at least a . and an extension.
  • The name of a directory or sub-directory will not contain a ..
    Time complexity required: O(n) where n is the size of the input string.

Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def lengthLongestPath(self, input):
"""
:type input: str
:rtype: int
"""
paths = input.split('\n')
tmp,max_len = [],0
for path in paths:
level,index = 0,path.rfind('\t')
if index == -1:
level = 1
else:
level = index + 2
path = path[index+1:]
while len(tmp) >= level:
tmp.pop()
tmp.append(path)
if '.' in path:
res = '/'.join(tmp)
max_len = max(len(res),max_len)
return max_len

leetcode 390. Elimination Game

发表于 2018-05-29 | 分类于 leetcode

There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.

We keep repeating the steps again, alternating left to right and right to left, until a single number remains.

Find the last number that remains starting with a list of length n.
Example:


Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

Output:
6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
def ltr(n):
if n <= 2:return n
return 2*rtl(n/2)

def rtl(n):
if n <= 2:return 1
if n%2 == 1:return 2*ltr(n/2)
return 2*ltr(n/2)-1

return ltr(n)

a faster solution with o(logN)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
head, step = 1, 1
left = True
while n > 1:
if left or n%2 == 1:
head += step
step *= 2
n >>= 1
left= not left
return head

Explain:
When will head be updated?

  • if we move from left
  • if we move from right and the total remaining number % 2 == 1
    like 2 4 6 8 10, we move from 10, we will take out 10, 6 and 2, head is deleted and move to 4
    like 2 4 6 8 10 12, we move from 12, we will take out 12, 8, 4, head is still remaining 2
    then we find a rule to update our head.

example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Let us start with head = 1, left = true, step = 1 (times 2 each turn), n= n(20)

we first move from left, we definitely need to move head to next position. (head = head + step)
So after first loop we will have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 - > 2 4 6 8 10 12 14 16 18 20
head = 2, left = false, step = 1 * 2 = 2, n= n/ 2 = 10

second loop, we move from right, in what situation we need to move head?
only if the n% 2 == 1, in this case we have 10 % 2 == 0, we don’t touch head.
so after this second loop we will have:
2 4 6 8 10 12 14 16 18 20 - > 2 6 10 14 18
head = 2, left = true, step = 2 * 2 = 4, n= n/ 2 = 5

third loop, we move from left, move head to next position
after third loop we will have:
2 6 10 14 18 - > 6 14
head = 6, left = false, step = 4 * 2 = 8, n= n/ 2 = 2

fourth loop, we move from right:
we have n(2) % 2 == 0, so head will not move
after this loop, we will have
6 14 - > 6
head = 6, left = true, step = 8 * 2 = 16, n= n/ 2 = 1

while loop end, return head

常用汇编指令

发表于 2018-05-29 | 分类于 linux

http://www.cnblogs.com/lxgeek/archive/2011/01/01/1923738.html

leetcode 391. Perfect Rectangle

发表于 2018-05-28 | 分类于 leetcode

我们有 N 个与坐标轴对齐的矩形, 其中 N > 0, 判断它们是否能精确地覆盖一个矩形区域。

每个矩形用左下角的点和右上角的点的坐标来表示。例如, 一个单位正方形可以表示为 [1,1,2,2]。 ( 左下角的点的坐标为 (1, 1) 以及右上角的点的坐标为 (2, 2) )。




示例1

rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [3,2,4,4],
  [1,3,2,4],
  [2,3,3,4]
]

返回 true。5个矩形一起可以精确地覆盖一个矩形区域。
示例2
rectangles = [
  [1,1,2,3],
  [1,3,2,4],
  [3,1,4,2],
  [3,2,4,4]
]

返回 false。两个矩形之间有间隔,无法覆盖成一个矩形。
示例3
rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [1,3,2,4],
  [3,2,4,4]
]

返回 false。图形顶端留有间隔,无法覆盖成一个矩形。
示例4
rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [1,3,2,4],
  [2,2,4,4]
]

返回 false。因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def isRectangleCover(self, rectangles):
#large rectangle area is equal to small rectangles
#large rectangle points in small rectangles points
if len(rectangles) == 0 or len(rectangles[0]) == 0:
return False
x1 = float("inf")
y1 = float("inf")
x2 = 0
y2 = 0
rec = set()
area = 0
for points in rectangles:
x1 = min(points[0],x1)
y1 = min(points[1],y1)
x2 = max(points[2],x2)
y2 = max(points[3],y2)
area += (points[3]-points[1])*(points[2]-points[0])
rec.remove((points[0],points[3])) if (points[0],points[3]) in rec else rec.add((points[0],points[3]))
rec.remove((points[0],points[1])) if (points[0],points[1]) in rec else rec.add((points[0],points[1]))
rec.remove((points[2],points[3])) if (points[2],points[3]) in rec else rec.add((points[2],points[3]))
rec.remove((points[2],points[1])) if (points[2],points[1]) in rec else rec.add((points[2],points[1]))
if (x1,y2) not in rec or (x2,y1) not in rec or (x1,y1) not in rec or (x2,y2) not in rec or len(rec) != 4:
return False
return area == (y2-y1)*(x2-x1)

leetcode 392. Is Subsequence

发表于 2018-05-25 | 分类于 leetcode

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).

Example 1:
s = “abc”, t = “ahbgdc”

Return true.

Example 2:
s = “axc”, t = “ahbgdc”

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, … , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

  • solution with loop

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class Solution(object):
    def isSubsequence(self, s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    if len(s) == 0:return True
    count = 0
    for c in t:
    if c == s[count]:
    count += 1
    if count == len(s):return True
    return False
  • solution with two points

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Solution:
    def isSubsequence(self, s, t):
    i = 0
    j = 0
    while i < len(s) and j < len(t):
    if s[i] == t[j]:
    i = i + 1
    j = j + 1
    else:
    j = j + 1
    return i == len(s)
  • solution with dp,it’s slow o(n^2)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
            int m = s.length(), n = t.length();
    if (m == 0) return true;
    int[][] dp = new int[m+1][n+1];
    for (int i = 0; i <= m; i++) {
    dp[i] = new int[n+1];
    }
    for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
    if (s.charAt(i-1) == t.charAt(j-1)) {
    dp[i][j] = dp[i-1][j-1] + 1;
    }
    else{
    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
    }
    }
    }
    return dp[m][n] == m;
    }

leetcode 399. Evaluate Division

发表于 2018-05-24 | 分类于 leetcode

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. 

The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
graph = collections.defaultdict(dict)
for (a,b),val in zip(equations,values):
graph[a][b] = val
graph[a][a] = graph[b][b] = 1.0
graph[b][a] = 1/val
for k in graph:
for i in graph[k]:
for j in graph[k]:
graph[i][j] = graph[i][k]*graph[k][j]
return [graph[a].get(b,-1.0) for a,b in queries]

leetcode 398. Random Pick Index

发表于 2018-05-23 | 分类于 leetcode

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:


int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);

  • my solution is memory limit exceeded

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import random
    import collections
    class Solution(object):

    def __init__(self, nums):
    self.nums = nums

    def pick(self, target):
    index_dict = collections.defaultdict(list)
    for i,n in enumerate(self.nums):
    index_dict[n].append(i)
    return random.choice(index_dict[target])
  • Reservoir Sampling solution

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import random
    import collections
    class Solution(object):

    def __init__(self, nums):
    self.nums = nums

    def pick(self, target):
    count, index = 0, 0
    for i, n in enumerate(self.nums):
    if n == target:
    count += 1
    rand = random.randint(1, count)
    if rand == count:
    index = i

    return index

leetcode 397. Integer Replacement

发表于 2018-05-22 | 分类于 leetcode

Given a positive integer n and you can do operations as follow:

  1. If n is even, replace n with n/2.
  2. If n is odd, you can replace n with eithern + 1 or n - 1.

What is the minimum number of replacements needed for n to become 1?

Example 1:

Input:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1

Example 2:


Input:
7
Output:
4
Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1

  • clear solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
d = {}
def helper(n):
if n == 1:
return 0
if n in d:
return d[n]
val = 0
if n%2 == 0:
val = 1 + helper(n/2)
else:
val = min(1+helper(n-1),1+helper(n+1))
d[n] = val
return val
return helper(n)
  • my solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
def helper(n):
if n == 1:
return 0
if n == 3:
return 2
val = 0
if n%2 == 0:
val = 1 + helper(n/2)
else:
val = min(1+helper(n-1),1+helper(n+1))

return val
return helper(n)

my solution recursion do not store ,slower than clear solution

leetcode 396. Rotate Function

发表于 2018-05-21 | 分类于 leetcode

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a “rotation function” F on A as follow:

F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].

Calculate the maximum value of F(0), F(1), ..., F(n-1).

Note:
n is guaranteed to be less than 10^5.

Example:


A = [4, 3, 2, 6]
F(0) = (0 4) + (1 3) + (2 2) + (3 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 6) + (1 4) + (2 3) + (3 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 2) + (1 6) + (2 4) + (3 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 3) + (1 2) + (2 6) + (3 4) = 0 + 2 + 12 + 12 = 26

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

  • my solution:
1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def maxRotateFunction(self, A):
if len(A) == 0:
return 0
n = len(A)
def f(A,k):
B = (A+A)[k:k+n]
v = 0
for i in range(n):
v += i*B[i]
return v
return max(f(A,i) for i in range(n))

this solution is o(n^2), cost 14s

  • clear solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def maxRotateFunction(self, A):
n = len(A)
v = 0
sumA = 0
for i in range(n):
v += i * A[i]
sumA += A[i]
max_v = v
for i in range(n - 1, 0, -1):
v = v + sumA - n * A[i]
max_v = max(max_v, v)
return max_v

this solution cost 0.02s

because f(k+1)-f(k) = nA[k] - sumA

f(k+1) = 0*A[k+1] + A[k+2] + 2*A[k+3]+…+(n-1)A[k+1+n-1]

A[k+n] = A[k]

f(k+1) = (n-1)*A[k]+0*A[k+1] + A[k+2] + 2*A[k+3]+…+(n-2)A[k+n-1]

f(k) = 0*A[k] + A[k+1] + 2*A[k+2]+…+(n-1)A[k+n-1]

so f(k+1)-f(k) = n*A[k] - (A[k] + A[k+1] +…+A[k+n-1])

= n*A[k] - sumA

1…141516…20

zhuanli

194 日志
9 分类
41 标签
GitHub
© 2018 — 2019 zhuanli
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4