118. Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res = [[1]]
for i in range(1,numRows):
res += [map(lambda x, y:x+y,res[-1]+[0],[0]+res[-1])]
return res[:numRows] # [[1]]+[0] -> [[1],0]
# [[1]]+[0,1] ->[[1],0,1]
# [[1]]+[[0]] -> [[1],[0]]
# [[1]]+0 -> error
# the code is elegant, but slow. the reason lies in the fact that it generates too much list while looping
# be careful when numRows is 0, res[:numRows] will return [] when it happens

119. Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
""" res = [1]
for i in range(0, rowIndex):
res = [ i+j for i,j in zip(res + [0], [0] + res)]
return res # list can't be added elementwisely with +

561. Array Partition I

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).

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sorted_nums=sorted(nums)
return sum(sorted_nums[::2])
# easy but not fast

566. Reshape the Matrix

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:

Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

Note:

  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if r*c != len(nums)*len(nums[0]):
return nums
else:
newList = [y for x in nums for y in x]
return [newList[i*c:i*c+c] for i in range(r)]
# not difficult

643. Maximum Average Subarray I

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note:

  1. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].
class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
sum_max=sum(nums[:k])
cur_sum=sum_max
for i in range(k,len(nums)):
cur_sum=cur_sum+nums[i]-nums[i-k]
if cur_sum>sum_max:
sum_max=cur_sum
return float(sum_max)/k
# the difference between '/' and '//' only exist in python3, not 2
# clear and fast

661. Image Smoother

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

Example 1:

Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

Note:

  1. The value in the given matrix is in the range of [0, 255].
  2. The length and width of the given matrix are in the range of [1, 150].
class Solution(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
r=len(M)
c=len(M[0])
for i in range(r):
M[i].append(-1)
M.append([-1 for i in range(c+1)])
N=[[0 for j in range(c)] for i in range(r)]
for i in range(r):
for j in range(c):
count = 0
sum_temp=0
for k in range(-1,2):
for l in range(-1,2):
if M[i+k][j+l] != -1:
count+=1
sum_temp+=M[i+k][j+l]
N[i][j]=sum_temp/count
return N
# use -1 to distinguish the arti_added elements
# utilize index -1 in python to optimize the realization

665. Non-decreasing Array

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note: The n belongs to [1, 10,000].

class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
cur, nxt = nums[:], nums[:]
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
cur[i]=nums[i+1]
nxt[i+1]=nums[i]
break
if cur==sorted(cur) or nxt==sorted(nxt):
return True
return False
# "==" can be used between lists, good!
# sorted() will return a new list

674. Longest Continuous Increasing Subsequence

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

Example 1:

Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.

Example 2:

Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1.

Note: Length of the array will not exceed 10,000.

class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return 0
max_len = 1
cur_max = 1
for i in range(len(nums)-1):
if nums[i+1] > nums[i]:
cur_max += 1
else:
max_len = max(max_len,cur_max)
cur_max = 1
return max(max_len,cur_max)
# easy

695. Max Area of Island

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
""" row,col = len(grid),len(grid[0]) def dfs(i,j): if 0<=i<row and 0<=j<col and grid[i][j] == 1:
grid[i][j]=0
return 1+dfs(i-1,j)+dfs(i+1,j)+dfs(i,j-1)+dfs(i,j+1)
else:
return 0 island = [dfs(i,j) for i in range(row) for j in range(col) if grid[i][j]] return max(island) if island else 0 # make it faster when not busy

697. Degree of an Array

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

Input: [1,2,2,3,1,4,2]
Output: 6

Note:

  • nums.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for i in range(len(nums)):
if nums[i] not in dic.keys():
dic[nums[i]]=[]
dic[nums[i]].append(i)
len_max = max(map(len,dic.values()))
shortest = 50000
for i in dic.itervalues():
if len(i) == len_max:
if i[-1]-i[0]+1 < shortest:
shortest = i[-1]-i[0]+1
return shortest
# too slow
# dic_obj.itervalues()

724. Find Pivot Index

Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Note:

  • The length of nums will be in the range [0, 10000].
  • Each element nums[i] will be an integer in the range [-1000, 1000].
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return -1
nums_sum=sum(nums)
cur_sum= 0
found = 0
for i in range(len(nums)):
if cur_sum*2 == nums_sum-nums[i]:
found =1
return i
cur_sum += nums[i]
if found == 0: return -1
# lele tested me with this before

747. Largest Number At Least Twice of Others

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.

Example 2:

Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.

Note:

  1. nums will have a length in the range [1, 50].
  2. Every nums[i] will be an integer in the range [0, 99].
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
""" max = 0
notfound = 0
for i in range(len(nums))[1:]:
if notfound == 1:
# if the previous array has not found the ideal number(even though max has recorded the index of the largest element), the variable will be alter to 0 only if the i-th element is greater than twice of the max_th element
if nums[i]>=nums[max]*2:
notfound = 0
max = i
elif nums[i]>nums[max]:
temp = max
max = i
i = temp
elif notfound == 0:
# if the previous array has found the ideal number(with max being its index), the ith element should either be greater than the max_th element or smaller than 1/2 of it, or, the current array has not found the ideal element, that is , notfound should be set to 1
if nums[i]>nums[max]:
temp = max
max = i
i = temp
if nums[max]>=nums[i]*2:
notfound = 0
else:
notfound = 1
if notfound == 1:
return -1
else:
return max

Leetcode with Python -> Array的更多相关文章

  1. LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  2. LeetCode专题-Python实现之第27题:Remove Element

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  3. LeetCode专题-Python实现之第14题:Longest Common Prefix

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  4. LeetCode专题-Python实现之第1题:Two Sum

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  5. 导航页-LeetCode专题-Python实现

    LeetCode专题-Python实现之第1题:Two Sum LeetCode专题-Python实现之第7题:Reverse Integer LeetCode专题-Python实现之第9题:Pali ...

  6. LeetCode:Convert Sorted Array to Binary Search Tree,Convert Sorted List to Binary Search Tree

    LeetCode:Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in asce ...

  7. LeetCode专题-Python实现之第28题: Implement strStr()

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  8. LeetCode专题-Python实现之第21题:Merge Two Sorted Lists

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  9. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

随机推荐

  1. LeetCode OJ Container With Most Water 容器的最大装水量

    题意:在坐标轴的x轴上的0,1,2,3,4....n处有n+1块木板,长度不一,任两块加上x轴即可构成一个容器,其装水面积为两板的间距与较短板长之积,以vector容器给出一系列值,分别代表在0,1, ...

  2. pat甲级1020中序后序求层序

    1020 Tree Traversals (25)(25 分) Suppose that all the keys in a binary tree are distinct positive int ...

  3. hdu-2066 一个人的旅行---模板题

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2066 题目大意: 求到目标点集合中的最短距离 解题思路: dijkstra算法求出每个点到该点的最短 ...

  4. Linux学习记录(二)

    1.远程连接工具的使用 实际开发中,Linux服务器都在其他的地方,我们要通过远程的方式去连接Linux并操作它,Linux远程的操作工具有很多,企业中常用的有Puttty.secureCRT.SSH ...

  5. js打印div指定区域内容

    <script> function myPrint(obj){ var newWindow=window.open("打印窗口","_blank") ...

  6. Java中的异常处理从概念到实例

    1.概念 采用新的异常处理机制 在以往的程序开发过程中,经常采用返回值进行处理.例如,在编写一个方法,可以返回一个状态代码,调用者根据状态代码判定出错与否.若状态代码表示一个错误,则调用这进行相应的处 ...

  7. Linux问题分析或解决_samba无法连接

    1. windows设置方面问题 问题:window能连接部分服务器的samba共享,一部分无法连接.报错如截图. 解决:前提---其他人连接都没有问题,发现有问题的连接服务器的电脑是win10,而w ...

  8. goaccess 安装

    今天尝试搭建goaccess,用于分析access.log文件,但安装并不顺利,小记一下自己遇到的问题及解决方法 系统环境:CentOS release 6.9 一.参照官网教程进行搭建 $ wget ...

  9. LOL游戏基本代码

    class Hero: def __init__(self, new_nickname, new_aggressivity, new_life_value, new_money, new_armor ...

  10. haystack(django的全文检索模块)

    haystack haystack是django开源的全文搜索框架 全文检索:标题可以检索,内容也可以检索 支持solr ,elasticsearch,whoosh 1.注册app 在setting. ...