deftwoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j]
1 2 3 4 5 6 7 8 9 10 11
deftwoSum(self, nums: List[int], target: int) -> List[int]: temp = [(n, i) for i, n in enumerate(nums)] temp.sort() i, j = 0, len(temp) - 1 while i < j: if temp[i][0] + temp[j][0] < target: i += 1 elif temp[i][0] + temp[j][0] > target: j -= 1 else: return [temp[i][1], temp[j][1]]
1 2 3 4 5 6
deftwoSum(self, nums: List[int], target: int) -> List[int]: nums_dict = {} for i, n in enumerate(nums): if target - n in nums_dict: return [nums_dict[target - n], i] nums_dict[n] = i
defspiralOrder(self, matrix: List[List[int]]) -> List[int]: ifnot matrix ornot matrix[0]: return [] res = [] top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1 while top <= bottom and left <= right: for i in range(left, right + 1): res.append(matrix[top][i]) top += 1 for i in range(top, bottom + 1): res.append(matrix[i][right]) # remember [i[[right] not [right][i] right -= 1 if top <= bottom: for i in range(right, left - 1, -1): res.append(matrix[bottom][i]) bottom -= 1 if left <= right: for i in range(bottom, top - 1, -1): res.append(matrix[i][left]) left += 1 return res
deffind_kth_smallest2(self, nums1, nums2, k): i, j = 0, 0 while i < len(nums1) and j < len(nums2) and k > 0: if nums1[i] <= nums2[j]: i += 1 else: j += 1 k -= 1 if i == len(nums1): # remember dont use (not nums1) return nums2[j + k] # remember use j+k rather than k if j == len(nums2): return nums1[i + k] return min(nums1[i], nums2[j])
deffind_kth_smallest3(self, nums1, nums2, i, j, k): if i >= len(nums1): # remember to use >= rather than == return nums2[j + k] if j == len(nums2): return nums1[i + k] if k == 0: return min(nums1[i], nums2[j]) num1 = nums1[i + k // 2] if i + k // 2 < len(nums1) else float('inf') # remember sys.maxsize not minus num2 = nums2[j + k // 2] if j + k // 2 < len(nums2) else float('inf') if num1 <= num2: # remember the steps are same by moving i and k, k + 1 return self.find_kth_smallest3(nums1, nums2, i + (k + 1) // 2, j, k - (k + 1) // 2) else: return self.find_kth_smallest3(nums1, nums2, i, j + (k + 1) // 2, k - (k + 1) // 2)
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".