diff --git a/ MovingAveragefromDataStream.py b/ MovingAveragefromDataStream.py new file mode 100644 index 0000000..820feb3 --- /dev/null +++ b/ MovingAveragefromDataStream.py @@ -0,0 +1,37 @@ +class MovingAverage(object): + + def __init__(self, size): + """ + Initialize your data structure here. + :type size: int + """ + self.Size = size + self.data = [None]*size + self.head = -1 + self.tail = -1 + + def next(self, val): + """ + :type val: int + :rtype: float + """ + if self.head == -1: + self.head = 0 + self.tail = 0 + self.data[0] = val + return float(val) + elif (self.tail+1) % self.Size != self.head: + self.tail += 1 + self.data[self.tail] = val + return float(sum(self.data[:self.tail+1]))/(self.tail-self.head+1) + else: + self.head = (self.head + 1) % self.Size + self.tail = (self.tail + 1) % self.Size + self.data[self.tail] = val + return float(sum(self.data))/self.Size + + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) diff --git a/DesignCircularQueue.py b/DesignCircularQueue.py new file mode 100644 index 0000000..409fde2 --- /dev/null +++ b/DesignCircularQueue.py @@ -0,0 +1,109 @@ +class MyCircularQueue(object): + + def __init__(self, k): + """ + Initialize your data structure here. Set the size of the queue to be k. + :type k: int + """ + self.size = k + self.data = [None]*k + self.head = -1 + self.tail = -1 + + def enQueue(self, value): + """ + Insert an element into the circular queue. Return true if the operation is successful. + :type value: int + :rtype: bool + """ + if self.isEmpty(): + self.head += 1 + self.tail += 1 + self.data[0] = value + return True + elif not self.isFull(): + if self.tail != self.size - 1: + self.tail += 1 + self.data[self.tail] = value + return True + else: + self.tail = 0 + self.data[self.tail] = value + return True + else: + return False + + + def deQueue(self): + """ + Delete an element from the circular queue. Return true if the operation is successful. + :rtype: bool + """ + if self.isEmpty(): + return False + elif self.head == self.tail: + self.head, self.tail = -1, -1 + return True + else: + if self.head != self.size - 1: + self.head += 1 + return True + else: + self.head = 0 + return True + + + + def Front(self): + """ + Get the front item from the queue. + :rtype: int + """ + if self.isEmpty(): + return -1 + else: + return self.data[self.head] + + + + def Rear(self): + """ + Get the last item from the queue. + :rtype: int + """ + if self.isEmpty(): + return -1 + else: + return self.data[self.tail] + + + + def isEmpty(self): + """ + Checks whether the circular queue is empty or not. + :rtype: bool + """ + if self.head == -1 and self.tail == -1: + return True + else: + return False + + + def isFull(self): + """ + Checks whether the circular queue is full or not. + :rtype: bool + """ + if self.head == ( self.tail + 1 ) % self.size: + return True + else: + return False + +# Your MyCircularQueue object will be instantiated and called as such: +# obj = MyCircularQueue(k) +# param_1 = obj.enQueue(value) +# param_2 = obj.deQueue() +# param_3 = obj.Front() +# param_4 = obj.Rear() +# param_5 = obj.isEmpty() +# param_6 = obj.isFull() diff --git a/leetCode_10.py b/leetCode_10.py new file mode 100644 index 0000000..0175a46 --- /dev/null +++ b/leetCode_10.py @@ -0,0 +1,17 @@ +''' +Write a function that takes a string as input and returns the string reversed. + +Example: +Given s = "hello", return "olleh". +''' + +class Solution: + def reverseString(self, s): + """ + :type s: str + :rtype: str + """ + ans = '' + for x in range(len(s)): + ans = ans + s[len(s)-x-1] + return ans diff --git a/leetCode_11.py b/leetCode_11.py new file mode 100644 index 0000000..8e9b3af --- /dev/null +++ b/leetCode_11.py @@ -0,0 +1,28 @@ +''' +Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. + +Example 1: +Input: [1,4,3,2] + +Output: 4 +Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). + +''' + +class Solution: + def arrayPairSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + + n=sorted(nums) + sum = 0 + for x in range(0,len(n),2): + sum = sum + n[x] + return sum + + +''' +return (sum(sorted(nums)[0::2])) +''' diff --git a/leetCode_12.py b/leetCode_12.py new file mode 100644 index 0000000..a00ad78 --- /dev/null +++ b/leetCode_12.py @@ -0,0 +1,37 @@ +''' +Given an array nums and a value val, remove all instances of that value in-place and return the new length. + +Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. + +The order of elements can be changed. It doesn't matter what you leave beyond the new length. + +Given nums = [0,1,2,2,3,0,4,2], val = 2, + +Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. + +Note that the order of those five elements can be arbitrary. + +It doesn't matter what values are set beyond the returned length. +''' + +class Solution: + def removeElement(self, nums, val): + """ + :type nums: List[int] + :type val: int + :rtype: int + """ + + + + + i,t,j = 0,len(nums),0 + + while j < t: + if nums[i] == val: + nums.remove(val) + i -= 1 + i += 1 + j += 1 + + return len(nums) diff --git a/leetCode_13.py b/leetCode_13.py new file mode 100644 index 0000000..b4fc7b7 --- /dev/null +++ b/leetCode_13.py @@ -0,0 +1,31 @@ +''' +Given a binary array, find the maximum number of consecutive 1s in this array. + +Example 1: +Input: [1,1,0,1,1,1] +Output: 3 +Explanation: The first two digits or the last three digits are consecutive 1s. + The maximum number of consecutive 1s is 3. +Note: + +The input array will only contain 0 and 1. +The length of input array is a positive integer and will not exceed 10,000 +''' +class Solution: + def findMaxConsecutiveOnes(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + rec,curRec = 0,0 + + for i in nums: + if i==1: + curRec += 1 + else: + if curRec>rec: + rec=curRec + curRec = 0 + if curRec>rec: + rec=curRec + return rec diff --git a/leetCode_14.py b/leetCode_14.py new file mode 100644 index 0000000..33d38b9 --- /dev/null +++ b/leetCode_14.py @@ -0,0 +1,41 @@ +''' +Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. + +Example: + +Input: s = 7, nums = [2,3,1,2,4,3] +Output: 2 +Explanation: the subarray [4,3] has the minimal length under the problem constraint. +Follow up: +If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). +''' +# 我不太懂最後這一行,為什麼既然已經用了O(n)的方法,還要找O(nlog n)的方法? + + +class Solution: + def minSubArrayLen(self, s, nums): + """ + :type s: int + :type nums: List[int] + :rtype: int + """ + + i,j,curSum=0,0,0 + curLen,ansLen=0,len(nums) + success = False + + for x in nums: + curSum = curSum + x + while curSum>=s: + success = True + curLen = j - i + 1 + if curLen =< ansLen: + ansLen = curLen + curSum = curSum - nums[i] + i += 1 + j += 1 + + if success: + return ansLen + else: + return 0 diff --git a/leetCode_15.py b/leetCode_15.py new file mode 100644 index 0000000..fa5d906 --- /dev/null +++ b/leetCode_15.py @@ -0,0 +1,47 @@ +''' +Given an array, rotate the array to the right by k steps, where k is non-negative. + +Example 1: + +Input: [1,2,3,4,5,6,7] and k = 3 +Output: [5,6,7,1,2,3,4] +Explanation: +rotate 1 steps to the right: [7,1,2,3,4,5,6] +rotate 2 steps to the right: [6,7,1,2,3,4,5] +rotate 3 steps to the right: [5,6,7,1,2,3,4] +Example 2: + +Input: [-1,-100,3,99] and k = 2 +Output: [3,99,-1,-100] +Explanation: +rotate 1 steps to the right: [99,-1,-100,3] +rotate 2 steps to the right: [3,99,-1,-100] +Note: + +Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. +Could you do it in-place with O(1) extra space? + +''' +class Solution: + def rotate(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + n = len(nums) + k = k % n + nums[:] = nums[n-k:] + nums[:n-k] + +# 以下是在討論區挖到的,可我還是不懂為什麼寫成第二種,nums就會被指向新的nums而第一種不會? +''' +A little important thing to be cautious: + +nums[:] = nums[n-k:] + nums[:n-k] +can't be written as: + +nums = nums[n-k:] + nums[:n-k] +on the OJ. + +The previous one can truly change the value of old nums, but the following one just changes its reference to a new nums not the value of old nums. +''' diff --git a/leetCode_16.py b/leetCode_16.py new file mode 100644 index 0000000..108746e --- /dev/null +++ b/leetCode_16.py @@ -0,0 +1,92 @@ +''' + +Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. + +Note that the row index starts from 0. + + +In Pascal's triangle, each number is the sum of the two numbers directly above it. + +Example: + +Input: 3 +Output: [1,3,3,1] +Follow up: + +Could you optimize your algorithm to use only O(k) extra space? +''' +class Solution: + def getRow(self, rowIndex): + """ + :type rowIndex: int + :rtype: List[int] + """ + if rowIndex==0: + return [1] + + curIndex = 1 + ans = [1,1] + +# 更新版有算進 O(k) extra space 嗎? + while rowIndex > curIndex: + i = len(ans) - 1 + ans.append(1) + while 1 <= i: + ans[i] = ans[i-1] + ans[i] + i -= 1 + curIndex += 1 + + return ans + + + +''' + while rowIndex > curIndex: + i = 0 +''' +# 傳指標和傳內容以後一定要注意 +''' + newRow = ans[:] + while curIndex > i: + i += 1 + newRow[i] = ans[i-1] + ans[i] + newRow.append(1) + ans = newRow + curIndex += 1 + + return ans +''' + +''' +class Solution: + def getRow(self, rowIndex): + """ + :type rowIndex: int + :rtype: List[int] + """ + inplaceRow = [] + for row in range(rowIndex+1): + inplaceRow.append(1) +''' +# 倒過來加就可以避免重複加到的問題 +''' + for i in reversed(range(1, len(inplaceRow)-1)): + inplaceRow[i] = inplaceRow[i-1]+inplaceRow[i] + return inplaceRow +''' + +''' +class Solution(object): + def getRow(self, rowIndex): + """ + :type rowIndex: int + :rtype: List[int] + """ + row = [1] +''' +# 直接複製出兩行回聲軟泥,加出新的一輪,下回合繼續 +''' + for _ in range(rowIndex): + row = [x + y for x, y in zip([0]+row, row+[0])] + return row +''' diff --git a/leetCode_17.py b/leetCode_17.py new file mode 100644 index 0000000..1b85e4a --- /dev/null +++ b/leetCode_17.py @@ -0,0 +1,57 @@ +''' +Given an input string, reverse the string word by word. + +Example: + +Input: "the sky is blue", +Output: "blue is sky the". +Note: + +A word is defined as a sequence of non-space characters. +Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. +You need to reduce multiple spaces between two words to a single space in the reversed string. +Follow up: For C programmers, try to solve it in-place in O(1) space. +''' +class Solution(object): + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + + w = False + tempW = '' + ans = '' + + for c in s: + if c == ' ' and w == False: + continue + elif c == ' ' and w == True: + w = False + ans = ' ' + tempW + ans + tempW = '' + else: + w = True + tempW = tempW + c + + if tempW != '': + ans = tempW + ans + return ans + else: + return ans[1:] + +''' +class Solution(object): + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + s = s.strip().split(' ') + s = map(lambda x: x.strip(), s)[::-1] + a = '' + for i in s: + if i: + a = a + ' ' + i + return a.strip() +''' diff --git a/leetCode_18.py b/leetCode_18.py new file mode 100644 index 0000000..32e08d2 --- /dev/null +++ b/leetCode_18.py @@ -0,0 +1,40 @@ +''' +Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. + +Example 1: +Input: "Let's take LeetCode contest" +Output: "s'teL ekat edoCteeL tsetnoc" +Note: In the string, each word is separated by single space and there will not be any extra space in the string. +''' + +class Solution(object): + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + + w = False + tempW = '' + ans = '' + + for c in s: + if c == ' ' and w == False: + continue + elif c == ' ' and w == True: + w = False + ans = ans + tempW + ' ' + tempW = '' + else: + w = True + tempW = c + tempW + + if tempW != '': + ans = ans + tempW + return ans + else: + return ans[:len(ans)-1] +''' + + return ' '.join(s.split()[::-1])[::-1] +''' diff --git a/leetCode_19.py b/leetCode_19.py new file mode 100644 index 0000000..df92af8 --- /dev/null +++ b/leetCode_19.py @@ -0,0 +1,38 @@ +''' +Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. + +Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. + +Example 1: + +Given nums = [1,1,2], + +Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. + +It doesn't matter what you leave beyond the returned length. +Example 2: + +Given nums = [0,0,1,1,1,2,2,3,3,4], + +Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. + +It doesn't matter what values are set beyond the returned length. +''' +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + + j,t = 1,len(nums) + + if len(nums) == 0: + return 0 + + for i in range(len(nums)): + if i > 0 and nums[i] != nums[i-1]: + nums[j] = nums[i] + j += 1 + + return j diff --git a/leetCode_20.py b/leetCode_20.py new file mode 100644 index 0000000..8eaf9bf --- /dev/null +++ b/leetCode_20.py @@ -0,0 +1,28 @@ +''' +Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. + +Example: + +Input: [0,1,0,3,12] +Output: [1,3,12,0,0] +Note: + +You must do this in-place without making a copy of the array. +Minimize the total number of operations. +''' +class Solution(object): + def moveZeroes(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + + if len(nums) > 0: + i = 0 + for j in range(len(nums)): + if nums[j] != 0 and j==i: + i += 1 + elif nums[j] != 0: + nums[i] = nums[j] + nums[j] = 0 + i += 1 diff --git a/leetCode_4.py b/leetCode_4.py new file mode 100644 index 0000000..aaaeb36 --- /dev/null +++ b/leetCode_4.py @@ -0,0 +1,71 @@ +''' +Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. + +Example: +Input: +[ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] +] +Output: [1,2,4,7,5,3,6,8,9] +Explanation: + +Note: +The total number of elements of the given matrix will not exceed 10,000. +''' + + + +class Solution: + def findDiagonalOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + + if matrix == []: return [] + + t = len(matrix) * len(matrix[0]) + + rlen = len(matrix) + clen = len(matrix[0]) + + r,c = 0,0 + + move = 1 + + ans = list() + + for i in range(t): + + ans.append(matrix[r][c]) + + next_r = r - move + next_c = c + move + + if rlen-1 < next_r or next_r < 0 or clen-1 < next_c or next_c < 0: + if move > 0: + next_r = r + next_c = c + 1 + + if rlen-1 < next_r or next_r < 0 or clen-1 < next_c or next_c < 0: + next_r = r + 1 + next_c = c + + move = move * (-1) + + else: + next_r = r + 1 + next_c = c + + if rlen-1 < next_r or next_r < 0 or clen-1 < next_c or next_c < 0: + next_r = r + next_c = c + 1 + + move = move * (-1) + + r = next_r + c = next_c + + return ans diff --git a/leetCode_5.py b/leetCode_5.py new file mode 100644 index 0000000..6d09a7d --- /dev/null +++ b/leetCode_5.py @@ -0,0 +1,84 @@ +''' +Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. + +Example 1: + +Input: +[ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] +] +Output: [1,2,3,6,9,8,7,4,5] +Example 2: + +Input: +[ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9,10,11,12] +] +Output: [1,2,3,4,8,12,11,10,9,5,6,7] +''' +class Solution: + def spiralOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + + if matrix == []: return [] + + t = len(matrix) * len(matrix[0]) + + rlen = len(matrix) + clen = len(matrix[0]) + + r,c = 0,-1 + + move = 1 + + ans = list() + + rowStep = rlen - 1 + cur_rowStep = 0 + columnStep = clen + cur_columnStep = 0 + + state = 'right' + + for i in range(t): + + if state == 'right': + c +=1 + ans.append(matrix[r][c]) + cur_columnStep += 1 + if cur_columnStep == columnStep: + state = 'down' + cur_columnStep = 0 + columnStep -= 1 + elif state == 'down': + r +=1 + ans.append(matrix[r][c]) + cur_rowStep += 1 + if cur_rowStep == rowStep: + state = 'left' + cur_rowStep = 0 + rowStep -= 1 + elif state == 'left': + c -=1 + ans.append(matrix[r][c]) + cur_columnStep += 1 + if cur_columnStep == columnStep: + state = 'up' + cur_columnStep = 0 + columnStep -= 1 + elif state == 'up': + r -=1 + ans.append(matrix[r][c]) + cur_rowStep += 1 + if cur_rowStep == rowStep: + state = 'right' + cur_rowStep = 0 + rowStep -= 1 + return ans diff --git a/leetCode_6.py b/leetCode_6.py new file mode 100644 index 0000000..8dc36ef --- /dev/null +++ b/leetCode_6.py @@ -0,0 +1,48 @@ +class Solution: + def generate(self, numRows): + """ + :type numRows: int + :rtype: List[List[int]] + """ + if numRows == 0: + return [] + elif numRows == 1: + return [[1]] + elif numRows == 2: + return [[1],[1,1]] + + ans = [[1],[1,1]] + + for i in range(3,numRows+1): + new_row = [1] + for x in range(i-2): + new_row.append(ans[i-2][x]+ans[i-2][x+1]) + new_row.append(1) + ans.extend([new_row]) + + return ans + + +# 這方法在操作陣列的手段很騷又迂迴 +''' +class Solution: + def generate(self, numRows): + """ + :type numRows: int + :rtype: List[List[int]] + """ + res = [] + if numRows < 3: + for i in range(1,numRows+1): + res.append([1] * i) + else: + lastRow = self.generate(numRows - 1) + lastRowPt = lastRow[-1] + currRow = [1] + [0] * (numRows - 2) + [1] + + for i in range(len(lastRowPt)-1): + currRow[i+1] = lastRowPt[i] + lastRowPt[i+1] + + res = lastRow + [currRow] + return res +''' diff --git a/leetCode_7.py b/leetCode_7.py new file mode 100644 index 0000000..31343ad --- /dev/null +++ b/leetCode_7.py @@ -0,0 +1,49 @@ +''' + +Given two binary strings, return their sum (also a binary string). + +The input strings are both non-empty and contains only characters 1 or 0. + +Example 1: + +Input: a = "11", b = "1" +Output: "100" +Example 2: + +Input: a = "1010", b = "1011" +Output: "10101" + +''' + +class Solution: + def addBinary(self, a, b): + """ + :type a: str + :type b: str + :rtype: str + """ + a2 = int(a) + b2 = int(b) + + ia,ib,p,ans = 0,0,1,0 + while a2 > 0: + ia = ia+(a2%10)*2*p + p = p*2 + a2 = a2//10 + p = 1 + while b2 > 0: + ib = ib+(b2%10)*2*p + p = p*2 + b2 = b2//10 + p = 1 + + c = ia + ib + while c > 0: + ans = ans + (c%2)*p + c = c//2 + p = p*10 + return str(ans) +# 這超賤 +''' +return format(int(a,2) + int(b,2),'b') +''' diff --git a/leetCode_8.py b/leetCode_8.py new file mode 100644 index 0000000..c774c17 --- /dev/null +++ b/leetCode_8.py @@ -0,0 +1,38 @@ +''' + +Implement strStr(). + +Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. + +Example 1: + +Input: haystack = "hello", needle = "ll" +Output: 2 +Example 2: + +Input: haystack = "aaaaa", needle = "bba" +Output: -1 +Clarification: + +What should we return when needle is an empty string? This is a great question to ask during an interview. + +For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). +''' + +class Solution: + def strStr(self, haystack, needle): + """ + :type haystack: str + :type needle: str + :rtype: int + """ + len_n = len(needle) + len_h = len(haystack) + + if needle == '': return 0 + + for i in range(len_h-len_n+1): + if haystack[i:i+len_n] == needle: + return i + + return -1 diff --git a/leetCode_9.py b/leetCode_9.py new file mode 100644 index 0000000..e2f3ac1 --- /dev/null +++ b/leetCode_9.py @@ -0,0 +1,72 @@ +''' +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + +Example 1: + +Input: ["flower","flow","flight"] +Output: "fl" +Example 2: + +Input: ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. +Note: + +All given inputs are in lowercase letters a-z. +''' + +class Solution: + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + t=len(strs) + + ans,i,corr,x = '',0,False,1 + + if t == 1: return strs[0] + elif t == 0 or '' in strs: return '' + + minStringIndex = strs.index(min(strs, key=len)) + strs[0],strs[minStringIndex] = strs[minStringIndex],strs[0] + + while True: + newC = strs[0][i] + while x <= t-1: + if newC != strs[x][i]: + corr = True + break + x += 1 + if corr: break + x = 1 + ans = ans + newC + i += 1 + if i >= len(strs[0]): break + + return ans + +# 這字串處理真的很漂亮 +''' +class Solution: + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + if not strs: + return ("") + length = min(strs, key=len) + strs.remove(length) +''' +# 尤其是這個部分,直接把最短字的每個字母編號,再逐一和其他各String的各個字母比較 +# 如果字母一不相等,就回傳前所有比對過的部分 +''' + for i, x in enumerate(length): + for item in strs: + if item[i] != x: + return(length[:i]) + return(length) +''' diff --git a/leetCode_l1-1.py b/leetCode_l1-1.py new file mode 100644 index 0000000..b6ca562 --- /dev/null +++ b/leetCode_l1-1.py @@ -0,0 +1,18 @@ +class Solution: + def pivotIndex(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + t = sum(nums) + l = t + for i in range(len(nums)): + + l = l - nums[i] + + + if l == (t-nums[i])/2: + return i + + return -1 + diff --git a/leetCode_l1-2.py b/leetCode_l1-2.py new file mode 100644 index 0000000..53ef767 --- /dev/null +++ b/leetCode_l1-2.py @@ -0,0 +1,64 @@ +''' +In a given integer array nums, there is always exactly one largest element. +Find whether the largest element in the array is at least twice as much as every other number in the array. +If it is, return the index of the largest element, otherwise return -1. + +Example 1: + +Input: nums = [3, 6, 1, 0] +Output: 1 +Explanation: 6 is the largest integer, and for every other number in the array x, +6 is more than twice as big as x. The index of value 6 is 1, so we return 1. + +else Output: -1 + +Note: + +nums will have a length in the range [1, 50]. +Every nums[i] will be an integer in the range [0, 99]. + ''' + + # 我以兩個list做存取,也要考慮過用mod欺負她的值介於0~99來回傳位置 +class Solution: + def dominantIndex(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n1=[0,0] + n2=[0,0] + + for i in range(len(nums)): + if nums[i] > n1[0]: + n2[0] = n1[0] + n1[0] = nums[i] + n1[1] = i + elif n1[0] > nums[i] > n2[0]: + n2[0] = nums[i] + n2[1] = i + + if n1[0] >= n2[0] * 2: + return n1[1] + + return -1 + +# 結果看其他人的解法,直接用num.index()找,阿倫出來評評理啊 +''' +class Solution: + def dominantIndex(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if len(nums)<=1: + return 0 + elif len(nums)>=2: + max_nums = max(nums) + max_index = nums.index(max_nums) + nums.remove(max_nums) + sec_nums = max(nums) + if max_nums>=2*sec_nums: + return max_index + else: + return -1 +''' diff --git a/leetCode_l1-3.py b/leetCode_l1-3.py new file mode 100644 index 0000000..71113da --- /dev/null +++ b/leetCode_l1-3.py @@ -0,0 +1,52 @@ +class Solution: + def plusOne(self, digits): + """ + :type digits: List[int] + :rtype: List[int] + """ + + r_digits = digits[::-1] + carry = 0 + + r_digits[0] = r_digits[0] + 1 + + if r_digits[0] >= 10: + r_digits[0] = 0 + carry = 1 + + n = 1 + + while carry != 0: + if n < len(r_digits): + r_digits[n] = r_digits[n] + 1 + if r_digits[n] == 10: + r_digits[n] = 0 + carry = 1 + n = n + 1 + else: + carry = 0 + else: + r_digits.append(1) + carry = 0 + + return r_digits[::-1] + +# 最後一行直接從前面加挺快的 +''' +class Solution: + def plusOne(self, digits): + """ + :type digits: List[int] + :rtype: List[int] + """ + carry = 0 + for i in range(len(digits)-1, -1, -1): + sum = digits[i] + if i == len(digits) - 1: sum += 1 + else: sum += carry + digits[i] = sum % 10 + carry = int(sum / 10) + if carry == 0: break + + return digits if carry == 0 else [1] + digits +'''