• API
• FAQ
• Tools
• Archive
daily pastebin goal
3%
SHARE
TWEET

Medium Arrays

a guest Aug 20th, 2018 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # Given an array, rotate the array to the right by k steps, where k is non-negative.
2.
3. class Solution:
4.     def rotate(self, nums, k):
5.         """
6.        :type nums: List[int]
7.        :type k: int
8.        :rtype: void Do not return anything, modify nums in-place instead.
9.        """
10.         k=k%len(nums)
11.         nums[:] = nums[-k:] + nums[:-k]
12.
13. ----------------------------------------------------------------------------
14. Given an array of integers, find if the array contains any duplicates.
15.
16. Your function should return true if any value appears at least twice in the array,
17. and it should return false if every element is distinct.
18.
19. class Solution:
20.     def containsDuplicate(self, nums):
21.         """
22.        :type nums: List[int]
23.        :rtype: bool
24.        """
25.         """"
26.        nums.sort()
27.        lastnum = None
28.        for num in nums:
29.            if lastnum != num:
30.                lastnum = num
31.            else:
32.                return True
33.        return False
34.        """
35.         return len(nums) != len(set(nums))
36. ----------------------------------------------------------------------------
37. # Given a non-empty array of integers, every element appears twice except for one. Find that single one.
38. class Solution:
39.     def singleNumber(self, nums):
40.         """
41.        :type nums: List[int]
42.        :rtype: int
43.        """
44.         result = 0
45.         for num in nums:
46.             result ^= num
47.         return result
48. ----------------------------------------------------------------------------
49. # Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
50. class Solution:
51.     def plusOne(self, digits):
52.         """
53.        :type digits: List[int]
54.        :rtype: List[int]
55.        """
56.         num = int(''.join(str(x) for x in digits))
57.         num = str(num + 1)
58.         result = []
59.         for digit in num:
60.             result.append(int(digit))
61.         return result
62.         """
63.        integer = int(''.join(map(str, digits))) + 1
64.        return list(map(int, str(integer)))
65.        """
66. ----------------------------------------------------------------------------
67. # Given an array nums, write a function to move all 0's to the end of it while
68. # maintaining the relative order of the non-zero elements.
69. class Solution:
70.     def moveZeroes(self, nums):
71.         """
72.        :type nums: List[int]
73.        :rtype: void Do not return anything, modify nums in-place instead.
74.        """
75.         for i in range(nums.count(0)):
76.             nums.append(nums.pop(nums.index(0)))
77.
78.
79. ----------------------------------------------------------------------------
80. # Given an array of integers, return indices of the two numbers such that they add up to a specific target
81. class Solution:
82.     def twoSum(self, nums, target):
83.         """
84.        :type nums: List[int]
85.        :type target: int
86.        :rtype: List[int]
87.        """
88.
89.         buff_dict = {}
90.         for i in range(len(nums)):
91.             if nums[i] in buff_dict:
92.                 return [buff_dict[nums[i]], i]
93.             else:
94.                 buff_dict[target - nums[i]] = i
95.         """
96.        comp = []
97.        for i in range(len(nums)):
98.            if nums[i] in comp:
99.                return [nums.index(target-nums[i]), i]
100.            else:
101.                comp.append(target-nums[i])
102.        """
103.
104. ----------------------------------------------------------------------------
105. # You are given an n x n 2D matrix representing an image.
106. # Rotate the image by 90 degrees (clockwise).
107. class Solution:
108.     def rotate(self, matrix):
109.         """
110.        :type matrix: List[List[int]]
111.        :rtype: void Do not return anything, modify matrix in-place instead.
112.        """
113.         matrix.reverse()
114.         for i in range(len(matrix)):
115.             for j in range(i):
116.                 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
117. ----------------------------------------------------------------------------
118. # 3 SUM
119. # Given an array nums of n integers, are there elements a, b, c in nums such
120. # that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
121. from collections import Counter
122.
123. class Solution:
124.     def threeSum(self, nums):
125.         """
126.        :type nums: List[int]
127.        :rtype: List[List[int]]
128.        """
129.         #Lets get a counter of the elements first
130.         freq = dict(Counter(nums))
131.         # Check if we have more than two 0 s for a three 0 sum of 0.
132.         if 0 in freq and freq[0] > 2:
133.           r = [
134.             [0, 0, 0]
135.           ]
136.         else :
137.           r = []
138.
139.         # Seperate out the negative and non negative numbers in two lists
140.         neg = sorted(filter(lambda x: x < 0, freq))
141.         nneg = sorted(filter(lambda x: x >= 0, freq))
142.         for n in neg:
143.           for nn in nneg: #Find last number we should look for to get a 3 sum of 0.
144.             targ = -(n + nn)
145.             if targ in freq:
146.                 #If the target number is a repeat of either of the first two we must
147.                 # check that it shows up more than once in the list through our freq count.
148.                 if targ in (n, nn) and freq[targ] > 1:
149.                     r.append([n, targ, nn])
150.                 # Make sure we dont get duplicate groups by making sure the target isnt meant to be a middle number.
151.                 elif targ < n:
152.                     r.append([n, targ, nn])
153.                 elif targ > nn:
154.                     r.append([n, targ, nn])
155.         return r
156. ----------------------------------------------------------------------------
157. # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
158. class Solution:
159.     def setZeroes(self, matrix):
160.         """
161.        :type matrix: List[List[int]]
162.        :rtype: void Do not return anything, modify matrix in-place instead.
163.        """
164.         r = len(matrix)
165.         c = len(matrix[0])
166.         rows = []
167.         columns = []
168.
169.         for i in range(r):
170.             for j in range(c):
171.                 if matrix[i][j]==0:
172.                     rows.append(i)
173.                     columns.append(j)
174.
175.         for row in rows:
176.             matrix[row] = [0]*c
177.
178.         for col in columns:
179.             for i in range(r):
180.                 matrix[i][col] = 0
181.
182. ----------------------------------------------------------------------------
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top