锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
2 #Runtime: 724 ms (Beats 27.21%)
3 #Memory: 40.3 MB (Beats 41.50%)
4
5 class Solution(object):
6 def findDiagonalOrder(self, nums):
7 """
8 :type nums: List[List[int]]
9 :rtype: List[int]
10 """
11 ans = defaultdict(list)
12 for x in xrange(len(nums)):
13 for y in xrange(len(nums[x])):
14 ans[x + y].append(nums[x][y])
15 return [y for x in ans.keys() for y in reversed(ans[x])]
]]>
鐢╬ython heapq鍋氭ā鎷?br />
2 #Runtime: 1029 ms (Beats 20%)
3 #Memory: 44.4 MB (Beats 25.71%)
4
5 class SeatManager(object):
6
7 def __init__(self, n):
8 """
9 :type n: int
10 """
11 self.seats = []
12 self.n = n
13 for i in xrange(1, n + 1):
14 heapq.heappush(self.seats, i)
15
16
17 def reserve(self):
18 """
19 :rtype: int
20 """
21 if self.seats > 0:
22 seat = heapq.heappop(self.seats)
23 return seat
24 return -1
25
26
27 def unreserve(self, seatNumber):
28 """
29 :type seatNumber: int
30 :rtype: None
31 """
32 heapq.heappush(self.seats, seatNumber)
33
34
35
36
37 # Your SeatManager object will be instantiated and called as such:
38 # obj = SeatManager(n)
39 # param_1 = obj.reserve()
40 # obj.unreserve(seatNumber)
]]>
#Runtime: 491 ms (Beats 40%)
#Memory: 23.8 MB (Beats 13.33%)
class Solution(object):
def getWinner(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
cnt = defaultdict(int)
n = len(arr)
mx = arr[0]
for i in xrange(1, n):
mx = max(mx, arr[i])
cnt[mx] += 1
if cnt[mx] >= k:
return mx
return mx
]]>
#Runtime: 491 ms (Beats 40%)
#Memory: 23.8 MB (Beats 13.33%)
class Solution(object):
def getWinner(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
cnt = defaultdict(int)
n = len(arr)
mx = arr[0]
for i in xrange(1, n):
mx = max(mx, arr[i])
cnt[mx] += 1
if cnt[mx] >= k:
return mx
return mx
]]>
2 #Runtime: 7 ms (Beats 97.10%)
3 #Memory: 13.3 MB (Beats 55.58%)
4
5 class MyStack(object):
6
7 def __init__(self):
8 self.que = deque()
9
10 def push(self, x):
11 """
12 :type x: int
13 :rtype: None
14 """
15 self.que.append(x)
16
17 def pop(self):
18 """
19 :rtype: int
20 """
21 for _ in range(len(self.que) - 1):
22 self.que.append(self.que.popleft())
23 return self.que.popleft()
24
25
26 def top(self):
27 """
28 :rtype: int
29 """
30 return self.que[-1]
31
32
33 def empty(self):
34 """
35 :rtype: bool
36 """
37 return len(self.que) == 0
38
39
40
41 # Your MyStack object will be instantiated and called as such:
42 # obj = MyStack()
43 # obj.push(x)
44 # param_2 = obj.pop()
45 # param_3 = obj.top()
46 # param_4 = obj.empty()
]]>
2 #Runtime: 14 ms (Beats 75.43%)
3 #Memory: 13.3 MB (Beats 67.24%)
4
5 class Solution(object):
6 def fullJustify(self, words, maxWidth):
7 """
8 :type words: List[str]
9 :type maxWidth: int
10 :rtype: List[str]
11 """
12 p = 0
13 ans = []
14 n_sp = []
15 while p < len(words):
16 tp = [words[p]]
17 l = len(words[p])
18 p += 1
19 while p < len(words) and l + len(words[p]) + 1 <= maxWidth:
20 l += len(words[p]) + 1
21 tp.append(words[p])
22 p += 1
23 n_sp = maxWidth - l
24 tp_ans = ""
25 if len(tp) == 1:
26 tp_ans += tp[0] + " " * n_sp
27 else:
28 if p == len(words):
29 for i in range(len(tp) - 1):
30 tp_ans += tp[i] + " "
31 tp_ans += tp[-1]
32 for _ in range(n_sp):
33 tp_ans += " "
34 else:
35 for i in range(len(tp) - 1):
36 tp_ans += tp[i] + " " * (1 + n_sp // (len(tp) - 1))
37 if (n_sp % (len(tp) - 1)) > i:
38 tp_ans += " "
39 tp_ans += tp[-1]
40 ans.append(tp_ans)
41 return ans
]]>
2 #Runtime: 98 ms (Beats 14.98%)
3 #Memory: 14.6 MB (Beats 16.21%)
4
5 class Solution(object):
6 def asteroidCollision(self, asteroids):
7 """
8 :type asteroids: List[int]
9 :rtype: List[int]
10 """
11 stk = [asteroids[0]]
12 for x in asteroids[1:]:
13 stk.append(x)
14 while len(stk) > 1 and stk[-2] > 0 and stk[-1] < 0:
15 pre1 = stk[-1]
16 pre2 = stk[-2]
17 stk.pop()
18 stk.pop()
19 if abs(pre1) != abs(pre2):
20 stk.append(pre1) if abs(pre1) > abs(pre2) else stk.append(pre2)
21 return stk
]]>
2 #Runtime: 990 ms (Beats 30.89%)
3 #Memory: 78.8 MB (Beats 74.63%)
4
5 class LRUCache(object):
6
7 def __init__(self, capacity):
8 """
9 :type capacity: int
10 """
11 self.cap = capacity
12 self.cache = OrderedDict()
13
14
15 def get(self, key):
16 """
17 :type key: int
18 :rtype: int
19 """
20 if key not in self.cache:
21 return -1
22 v = self.cache.pop(key)
23 self.cache[key] = v
24 return v
25
26
27 def put(self, key, value):
28 """
29 :type key: int
30 :type value: int
31 :rtype: None
32 """
33 if key in self.cache:
34 self.cache.pop(key)
35 elif len(self.cache) == self.cap:
36 self.cache.popitem(last=False)
37 self.cache[key] = value
38
39
40
41 # Your LRUCache object will be instantiated and called as such:
42 # obj = LRUCache(capacity)
43 # param_1 = obj.get(key)
44 # obj.put(key,value)
]]>
#Runtime: 322 ms (Beats 65.73%)
#Memory: 17.6 MB (Beats 31.25%)
class Solution(object):
def longestSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
one = []
zero = []
ans = 0
t0, t1 = 0, 0
if not nums[0]:
one.append(0)
for j in range(0, len(nums)):
if nums[j]:
if j == 0 or nums[j - 1]:
t1 += 1
else:
if t0:
zero.append(t0)
t1 = 1
t0 = 0
else:
if j == 0 or nums[j - 1] == 0:
t0 += 1
else:
if t1:
one.append(t1)
t1 = 0
t0 = 1
if t1:
one.append(t1)
if t0:
zero.append(t0)
one.append(0)
if not len(zero):
return one[0] - 1
for i in range(0, len(one)):
if i and zero[i - 1] == 1:
ans = max(ans, one[i - 1] + one[i])
else:
ans = max(ans, one[i])
return ans
]]>
2 #Runtime: 51 ms (Beats 21.61%)
3 #Memory: 16.2 MB (Beats 64.73%)
4
5 class Solution:
6 def summaryRanges(self, nums: List[int]) -> List[str]:
7 ans = []
8 for i, x in enumerate(nums):
9 if ans and ans[-1][1] == x - 1:
10 ans[-1][1] = x
11 else:
12 ans.append([x, x])
13 return [f'{x}->{y}' if x != y else f'{x}' for x, y in ans]
]]>
2 #Runtime: 706 ms (Beats 30.51%)
3 #Memory: 45.6 MB (Beats 66.10%)
4
5 class SnapshotArray(object):
6
7 def __init__(self, length):
8 """
9 :type length: int
10 """
11 self.cur_arr = [0] * length
12 self.his_arr = [[0] for _ in range(length)]
13 self.modifed_idx_list = set()
14 self.snap_id = 0
15 self.snap_id_arr = [[-1] for _ in range(length)]
16
17
18 def set(self, index, val):
19 """
20 :type index: int
21 :type val: int
22 :rtype: None
23 """
24 if self.his_arr[index][-1] == val:
25 if index in self.modifed_idx_list:
26 self.modifed_idx_list.remove(index)
27 return
28 self.cur_arr[index] = val
29 if index not in self.modifed_idx_list:
30 self.modifed_idx_list.add(index)
31
32
33 def snap(self):
34 """
35 :rtype: int
36 """
37 for i in self.modifed_idx_list:
38 self.snap_id_arr[i].append(self.snap_id)
39 self.his_arr[i].append(self.cur_arr[i])
40 self.modifed_idx_list.clear()
41 self.snap_id += 1
42 return self.snap_id - 1
43
44
45 def get(self, index, snap_id):
46 """
47 :type index: int
48 :type snap_id: int
49 :rtype: int
50 """
51 arr = self.snap_id_arr[index]
52 l, r = 1, len(arr)
53 while l < r:
54 mid = (l + r) // 2
55 if arr[mid] <= snap_id:
56 l = mid + 1
57 else:
58 r = mid
59 return self.his_arr[index][l - 1]
60
61
62
63 # Your SnapshotArray object will be instantiated and called as such:
64 # obj = SnapshotArray(length)
65 # obj.set(index,val)
66 # param_2 = obj.snap()
67 # param_3 = obj.get(index,snap_id)
]]>
2 #Runtime: 221 ms (Beats 56.41%)
3 #Memory: 25.4 MB (Beats 71.79%)
4
5 class UndergroundSystem(object):
6
7 def __init__(self):
8 self.trip_cur = {}
9 self.trip_his_data = {}
10
11
12 def checkIn(self, id, stationName, t):
13 """
14 :type id: int
15 :type stationName: str
16 :type t: int
17 :rtype: None
18 """
19 self.trip_cur[id] = (stationName, t)
20
21
22 def checkOut(self, id, stationName, t):
23 """
24 :type id: int
25 :type stationName: str
26 :type t: int
27 :rtype: None
28 """
29 sta, st = self.trip_cur.pop(id)
30 total_time, cnt = self.trip_his_data.get((sta, stationName), (0, 0))
31 self.trip_his_data[(sta, stationName)] = (total_time + t - st, cnt + 1)
32
33 def getAverageTime(self, startStation, endStation):
34 """
35 :type startStation: str
36 :type endStation: str
37 :rtype: float
38 """
39 total_time, cnt = self.trip_his_data.get((startStation, endStation))
40 return 1.0 * total_time / cnt
41
42
43
44 # Your UndergroundSystem object will be instantiated and called as such:
45 # obj = UndergroundSystem()
46 # obj.checkIn(id,stationName,t)
47 # obj.checkOut(id,stationName,t)
48 # param_3 = obj.getAverageTime(startStation,endStation)
]]>
2 #Runtime: 11 ms (Beats 96.98%)
3 #Memory: 13.2 MB (Beats 99.66%)
4
5 class Solution(object):
6 def generateMatrix(self, n):
7 """
8 :type n: int
9 :rtype: List[List[int]]
10 """
11 fg = [[0] * n for _ in range(n)]
12 fg[0][0] = 1
13 i, j, cnt, t = 0, 0, 1, 0
14 while cnt < n**2:
15 if t % 4 == 0:
16 while j < n - 1 and not fg[i][j + 1]:
17 j += 1
18 cnt += 1
19 fg[i][j] = cnt
20 elif t % 4 == 1:
21 while i < n - 1 and not fg[i + 1][j]:
22 i += 1
23 cnt += 1
24 fg[i][j] = cnt
25 elif t % 4 == 2:
26 while j >= 0 and not fg[i][j - 1]:
27 j -= 1
28 cnt += 1
29 fg[i][j] = cnt
30 elif t % 4 == 3:
31 while i >= 0 and not fg[i - 1][j]:
32 i -= 1
33 cnt += 1
34 fg[i][j] = cnt
35 t += 1
36 return fg
]]>
[1,2,3],
[4,5,6],
[7,8,9]]
2 #Runtime: 18 ms (Beats 50.87%)
3 #Memory: 13.3 MB (Beats 90.64%)
4
5 class Solution(object):
6 def spiralOrder(self, matrix):
7 """
8 :type matrix: List[List[int]]
9 :rtype: List[int]
10 """
11 fg = [[0] * len(matrix[0]) for _ in range(len(matrix))]
12 ans = [matrix[0][0]]
13 fg[0][0] = 1
14 i, j, cnt, t = 0, 0, 1, 0
15 while cnt < len(matrix) * len(matrix[0]):
16 if t % 4 == 0:
17 while j < len(matrix[0]) - 1 and not fg[i][j + 1]:
18 j += 1
19 ans.append(matrix[i][j])
20 fg[i][j] = 1
21 cnt += 1
22 elif t % 4 == 1:
23 while i < len(matrix) - 1 and not fg[i + 1][j]:
24 i += 1
25 ans.append(matrix[i][j])
26 fg[i][j] = 1
27 cnt += 1
28 elif t % 4 == 2:
29 while j >= 0 and not fg[i][j - 1]:
30 j -= 1
31 ans.append(matrix[i][j])
32 fg[i][j] = 1
33 cnt += 1
34 elif t % 4 == 3:
35 while i >= 0 and not fg[i - 1][j]:
36 i -= 1
37 ans.append(matrix[i][j])
38 fg[i][j] = 1
39 cnt += 1
40 t += 1
41 return ans
]]>
2 #Runtime: 47 ms (Beats 70%)
3 #Memory: 13.9 MB (Beats 15%)
4
5 class Solution(object):
6 def predictPartyVictory(self, senate):
7 """
8 :type senate: str
9 :rtype: str
10 """
11 n = len(senate)
12 s, fg = set(), [False] * n
13 b_d = b_r = 0
14 while len(s) != 1:
15 s = set()
16 for i in range(n):
17 if not fg[i]:
18 if senate[i] == 'R':
19 if b_r > 0:
20 b_r -= 1
21 fg[i] = True
22 else:
23 b_d += 1
24 s.add('R')
25 else:
26 if b_d > 0:
27 b_d -= 1
28 fg[i] = True
29 else:
30 b_r += 1
31 s.add('D')
32 return 'Radiant' if 'R' in s else 'Dire'
]]>
2 #Runtime: 223 ms (Beats 35.71%)
3 #Memory: 14.2 MB (Beats 14.29%)
4
5 class SmallestInfiniteSet(object):
6
7 def __init__(self):
8 self.hq = []
9 for i in range(1, 1001):
10 heapq.heappush(self.hq, i)
11
12 def popSmallest(self):
13 """
14 :rtype: int
15 """
16 return heapq.heappop(self.hq)
17
18
19 def addBack(self, num):
20 """
21 :type num: int
22 :rtype: None
23 """
24 if num not in self.hq:
25 heapq.heappush(self.hq, num)
26
27
28 # Your SmallestInfiniteSet object will be instantiated and called as such:
29 # obj = SmallestInfiniteSet()
30 # param_1 = obj.popSmallest()
31 # obj.addBack(num)
]]>
2 #Runtime: 29 ms (Beats 83.46%)
3 #Memory: 13.9 MB (Beats 47.65%)
4
5 class Solution:
6 def lastStoneWeight(self, stones: List[int]) -> int:
7 hp = []
8 for st in stones:
9 heapq.heappush(hp, -st)
10 while len(hp) >= 2:
11 s1 = heapq.heappop(hp)
12 s2 = heapq.heappop(hp)
13 if s2 > s1:
14 heapq.heappush(hp, s1 - s2)
15 return abs(hp[0]) if hp else 0
]]>
2 #Runtime: 57 ms (Beats 23.66%)
3 #Memory: 13.6 MB (Beats 67.74%)
4
5 class Solution(object):
6 def validateStackSequences(self, pushed, popped):
7 """
8 :type pushed: List[int]
9 :type popped: List[int]
10 :rtype: bool
11 """
12 stk = []
13 p1, p2 = 0, 0
14 while p1 < len(pushed) or p2 < len(popped):
15 if stk and p2 < len(popped) and stk[-1] == popped[p2]:
16 stk.pop()
17 p2 += 1
18 elif p1 < len(pushed):
19 stk.append(pushed[p1])
20 p1 += 1
21 else:
22 return False
23 if p1 == len(pushed) and p2 == len(popped):
24 return True
25 return False
]]>
2 #Runtime: 15 ms (Beats 93.49%)
3 #Memory: 13.7 MB (Beats 13.73%)
4
5 class Solution(object):
6 def simplifyPath(self, path):
7 """
8 :type path: str
9 :rtype: str
10 """
11 ans = []
12 sub_folders = path.split("/")
13 for sub_folder in sub_folders:
14 if sub_folder == "." or not sub_folder:
15 continue
16 elif sub_folder == "..":
17 if ans:
18 ans.pop()
19 else:
20 ans.append(sub_folder)
21 return "/" + "/".join(ans)
]]>
2 #Runtime: 193 ms (Beats 79.49%)
3 #Memory: 16.5 MB (Beats 54.58%)
4
5 class BrowserHistory(object):
6
7 def __init__(self, homepage):
8 """
9 :type homepage: str
10 """
11 self.history = [homepage]
12 self.pos = 0
13
14
15 def visit(self, url):
16 """
17 :type url: str
18 :rtype: None
19 """
20 self.history = self.history[:self.pos+1] + [url]
21 self.pos += 1
22
23
24 def back(self, steps):
25 """
26 :type steps: int
27 :rtype: str
28 """
29 self.pos = max(0, self.pos - steps)
30 return self.history[self.pos]
31
32
33 def forward(self, steps):
34 """
35 :type steps: int
36 :rtype: str
37 """
38 self.pos = min(len(self.history) - 1, self.pos + steps)
39 return self.history[self.pos]
40
41
42 # Your BrowserHistory object will be instantiated and called as such:
43 # obj = BrowserHistory(homepage)
44 # obj.visit(url)
45 # param_2 = obj.back(steps)
46 # param_3 = obj.forward(steps)
]]>
鐩存帴妯℃嫙鍗沖彲錛宲ython鍐欏緱姣旇緝鐑?br />
C++鐗堬細
2 #Runtime: 88 ms (Beats 13.2%)
3
4 class Solution {
5 public:
6 string convert(string s, int nRows) {
7 if(nRows == 1) return s;
8 string res;
9 int i = 0, j = 0, n = s.length();
10 while(j < s.length()) {
11 res.push_back(s[j]);
12 j += 2 * nRows - 2;
13 }
14 for(i = 1; i < nRows - 1; ++i) {
15 j = i;
16 while(j < s.length()) {
17 res.push_back(s[j]);
18 j += 2 * nRows - 2 * (i + 1);
19 if(j < s.length()) {
20 res.push_back(s[j]);
21 j += 2 * i;
22 }
23 }
24 }
25 j = nRows - 1;
26 while(j < s.length()) {
27 res.push_back(s[j]);
28 j += 2 * nRows - 2;
29 }
30 return res;
31 }
32 };
Python鐗堬細
2 #Runtime: 1107 ms (Beats 10.51%)
3 #Memory: 21.3 MB (Beats 5.28%)
4
5 class Solution(object):
6 def convert(self, s, numRows):
7 """
8 :type s: str
9 :type numRows: int
10 :rtype: str
11 """
12 if numRows == 1:
13 return s
14 col, i = 0, 0
15 ans = []
16 while i < len(s):
17 if col % (numRows - 1) == 0:
18 t = []
19 for j in range(numRows):
20 if i >= len(s):
21 t.append(' ')
22 else:
23 t.append(s[i])
24 i += 1
25 else:
26 t= []
27 for j in range(numRows - 1, -1, -1):
28 if j % (numRows - 1) == col % (numRows - 1):
29 t.append(s[i])
30 i += 1
31 else:
32 t.append(' ')
33 ans.append(t)
34 col += 1
35 ans = list(map(list, zip(*ans)))
36 ans = [i for item in ans for i in item]
37 ans = ''.join(ans)
38 return ans.replace(' ', '')
]]>
2 #Runtime: 1065 ms (Beats 44.83%)
3 #Memory: 88.8 MB (Beats 13.79%)
4
5 class Obj:
6 def __init__(self, key, val, cnt):
7 self.key = key
8 self.val = val
9 self.cnt = cnt
10
11
12 class LFUCache(object):
13 def __init__(self, capacity):
14 """
15 :type capacity: int
16 """
17 self.cap = capacity
18 self.obj_keys = {}
19 self.obj_cnt = defaultdict(OrderedDict)
20 self.min_cnt = None
21
22
23 def get(self, key):
24 """
25 :type key: int
26 :rtype: int
27 """
28 if key not in self.obj_keys:
29 return -1
30 obj = self.obj_keys[key]
31 del self.obj_cnt[obj.cnt][key]
32 if not self.obj_cnt[obj.cnt]:
33 del self.obj_cnt[obj.cnt]
34 obj.cnt += 1
35 self.obj_cnt[obj.cnt][key] = obj
36 if not self.obj_cnt[self.min_cnt]:
37 self.min_cnt += 1
38 return obj.val
39
40
41 def put(self, key, value):
42 """
43 :type key: int
44 :type value: int
45 :rtype: None
46 """
47 if not self.cap:
48 return
49 if key in self.obj_keys:
50 self.obj_keys[key].val = value
51 self.get(key)
52 return
53 if len(self.obj_keys) == self.cap:
54 k, n = self.obj_cnt[self.min_cnt].popitem(last=False)
55 del self.obj_keys[k]
56 self.obj_cnt[1][key] = self.obj_keys[key] = Obj(key, value, 1)
57 self.min_cnt = 1
58 return
59
60
61 # Your LFUCache object will be instantiated and called as such:
62 # obj = LFUCache(capacity)
63 # param_1 = obj.get(key)
64 # obj.put(key,value)
]]>
SummaryRanges() -> Initializes the object with an empty stream.
Discussion涓湁浜轟嬌鐢╬ython鐨凷orted List錛屽叾瀹炰笉蹇咃紝鍙傝?>https://leetcode.com/problems/data-stream-as-disjoint-intervals/solutions/531106/python-solution-using-bisect-to-do-binary-search-beating-99-5-in-time/
鍒濆鍖栦袱涓猧ntervals錛歔[-10001, -10001], [10001, 10001]] 錛堟瘮data stream灝?鎴栬呭ぇ1鍗沖彲錛夛紝姣忔鎻掑叆鏃惰皟鐢╞isect.bisect榪斿洖璇ユ彃鍏ュ湪浣曞錛岄氳繃鍒ゆ柇褰撳墠瑕佹彃鍏ョ殑鍊兼槸鍚︿笌鍓嶄竴涓垨鑰呭悗涓涓尯闂存湁overlap鏉ュ喅瀹氭槸鍚﹂渶瑕佸悎騫跺尯闂?br />
2 #Runtime: 115 ms (Beats 100%)
3 #Memory: 18.5 MB (Beats 88.46%)
4
5 class SummaryRanges(object):
6
7 def __init__(self):
8 self.ds = [[-10001, -10001], [10001, 10001]]
9
10 def addNum(self, value):
11 """
12 :type value: int
13 :rtype: None
14 """
15 idx = bisect.bisect(self.ds, [value])
16 l1, l2 = self.ds[idx - 1]
17 r1, r2 = self.ds[idx]
18 if l2 == value - 1 and r1 == value + 1:
19 self.ds = self.ds[ : idx - 1] + [[l1, r2]] + self.ds[idx + 1 : ]
20 elif l2 == value - 1:
21 self.ds[idx - 1][1] = value
22 elif r1 == value + 1:
23 self.ds[idx][0] = value
24 elif l2 < value - 1 and r1 > value + 1:
25 self.ds = self.ds[ : idx] + [[value, value]] + self.ds[idx : ]
26
27
28 def getIntervals(self):
29 """
30 :rtype: List[List[int]]
31 """
32 return self.ds[1 : -1]
33
34
35
36 # Your SummaryRanges object will be instantiated and called as such:
37 # obj = SummaryRanges()
38 # obj.addNum(value)
39 # param_2 = obj.getIntervals()
]]>
2 #Runtime: 47 ms (Beats 98.92%)
3 #Memory: 16.7 MB (Beats 94.85%)
4
5 class Solution(object):
6 def insert(self, intervals, newInterval):
7 """
8 :type intervals: List[List[int]]
9 :type newInterval: List[int]
10 :rtype: List[List[int]]
11 """
12 ans = []
13 i = 0
14 fg = 0
15 while i < len(intervals) :
16 if intervals[i][0] > newInterval[1]:
17 if not fg:
18 ans.append([newInterval[0], newInterval[1]])
19 fg = 1
20 ans.append([intervals[i][0], intervals[i][1]])
21 i += 1
22 continue
23 if intervals[i][1] < newInterval[0]:
24 ans.append([intervals[i][0], intervals[i][1]])
25 i += 1
26 continue
27 p1 = min(newInterval[0], intervals[i][0])
28 while i < len(intervals) and intervals[i][1] < newInterval[1]:
29 i += 1
30 if i == len(intervals):
31 p2 = newInterval[1]
32 ans.append([p1, p2])
33 fg = 1
34 else:
35 if intervals[i][0] > newInterval[1]:
36 p2 = newInterval[1]
37 ans.append([p1, p2])
38 ans.append([intervals[i][0], intervals[i][1]])
39 else:
40 p2 = intervals[i][1]
41 ans.append([p1, p2])
42 fg = 1
43 i += 1
44 continue
45 if not fg:
46 ans.append([newInterval[0], newInterval[1]])
47 return ans
]]>
2 #Runtime: 640 ms
3 #Memory Usage: 16.7 MB
4
5 class Solution(object):
6 def calculate_brackets_removed(self, stk):
7 pre = 0
8 i = 0
9 while i < len(stk):
10 if stk[i] == '-' and not i:
11 stk[i + 1] = - stk[i + 1]
12 i += 1
13 elif isinstance(stk[i], int):
14 pre = stk[i]
15 i += 1
16 elif (stk[i] == '+' or stk[i] == '-') and i:
17 pre = self.cal(stk[i], pre, stk[i + 1])
18 i = i + 2
19 return pre
20
21 def cal(self, op, a, b):
22 if op == '+':
23 return a + b
24 if op == '-':
25 return a - b
26
27 def calculate(self, s):
28 """
29 :type s: str
30 :rtype: int
31 """
32 stk = []
33 p = 0
34 for i in s:
35 if i == ' ':
36 continue
37 if i == '(':
38 stk.append(i)
39 elif i.isnumeric():
40 if stk and isinstance(stk[-1], int):
41 t = int(stk[-1]) * 10 + int(i)
42 stk.pop()
43 stk.append(t)
44 else:
45 stk.append(int(i))
46 elif i == ')':
47 stk_rev = stk[::-1]
48 idx = len(stk) - (stk_rev.index("(") + 1)
49 t = self.calculate_brackets_removed(stk[idx + 1 : ])
50 del stk[idx : ]
51 stk.append(t)
52 elif i == '+' or i == '-':
53 stk.append(i)
54 return self.calculate_brackets_removed(stk)
]]>
]]>
]]>
]]>
棰樻剰鏄嵃鍒峰垏鍓插悕鐗囷紝鍗扮殑鏃跺欒A*B寮犱竴璧峰嵃鍒鳳紝姣忓紶鍚嶇墖澶у皬涓篊*D錛屽嵃鍒風焊寮犲ぇ灝廍*F錛岄棶鍗板畬涔嬪悗鑷沖皯鍒囦竴鍒鑳芥妸鍚嶇墖閮藉垎寮(涓嶈兘鎶婂悕鐗囧彔鍦ㄤ竴璧蜂竴鍒鍒?錛屾槑鐧芥剰鎬濅箣鍚庡氨鏄劇劧澶ф按涓閬撲簡~~
//Problem: 1791 User: Uriel
//Memory: 368K Time: 0MS
//Language: G++ Result: Accepted
//Simulation
//2010.08.11
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
#define INF 100000000
int A,B,C,D,E,F,minx,cut;

int main()
{
int hh,ww;
while(scanf("%d %d %d %d %d %d",&C,&D,&A,&B,&E,&F),A|B|C|D|E|F)
{
minx=INF;
if(A>B)swap(A,B);
if(C>D)swap(C,D);
if(E>F)swap(E,F);
//-----------------------------------------------case 1
cut=0;
hh=A*C;ww=B*D;
if(hh>E || ww>F)goto case2;
if(E>hh)cut++;
if(F>ww)cut++;
cut+=C*D-1;
if(cut<minx)minx=cut;
//-----------------------------------------------case 2
case2: cut=0;
hh=A*D;ww=B*C;
if(hh>ww)swap(hh,ww);
if(hh>E || ww>F)goto flag;
if(E>hh)cut++;
if(F>ww)cut++;
cut+=C*D-1;
if(cut<minx)minx=cut;
flag: if(minx<INF)printf("The minimum number of cuts is %d.\n",minx);
else
puts("The paper is too small.");
}
return 0;
}
]]>
]]>