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. jq实现剪裁图片设置为头像

    有时候我们需要设置为这样,就是将某些图片设置为剪裁成设置的尺寸:就是这样的 插件的地址: http://www.htmleaf.com/jQuery/Image-Effects/20150421171 ...

  2. linux 命令——51 lsof(转)

    lsof(list open files) 是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件.所以 如传输控制 ...

  3. SAP成都研究院非典型程序猿,菜园子小哥:当我用UI5诊断工具时我用些什么

    身边有些年轻同事曾经向我表达过这种困扰:尽管完成日常工作没有任何问题,但是还想更进一步,把代码写得更好些,做到精益求精.现在写的代码能实现功能,但是不知道可以怎样写得更好. 除了阅读优秀的开源库开源框 ...

  4. 使用HANA Web-based Development Workbench创建最简单的Server Side JavaScript

    服务器端的JavaScript, 看下wikipedia的介绍: https://en.wikipedia.org/wiki/JavaScript#Server-side_JavaScript Ser ...

  5. Python核心编程——正则表达式

    本篇博客都是我认真读之后写的,有些地方和书上的语句一样…… 1.简介 正则表达式为高级的文本模式匹配.抽取.与/或文本形式的搜索和替换功能提供了基础.简单地说,正则表达式(简称regex)是一些由字符 ...

  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getSer

    这其实就是 获得应用的根url,比如说你的应用的根路径是 http://localhost:8080,那么你列出的代码就是为basePath赋值为 http://localhost:8080.具体点: ...

  7. OpenLayers项目分析——(一)项目介绍

    OpenLayers 是由MetaCarta公司开发的,用于WebGIS客户端的JavaScript包,目前的最高版本是2.7 V,通过BSD License 发行.它实现访问地理空间数据的方法都符合 ...

  8. objective C 内存管理及属性方法具体解释

    oc为每一个对象提供一个内部计数器.这个计数器跟踪对象的引用计数,当对象被创建或拷贝时.引用计数为1.每次保持对象时,调用retain接口.引用计数加1.假设不需要这个对象时调用release,引用计 ...

  9. python_15_os

    import os #1. os.system('dir') #2 cmd_res=os.system('dir')#执行命令不保存结果 print("-------",cmd_r ...

  10. python序列化(数据本地存放持久性存储)和反序列化

    http://blog.csdn.net/uestcyao/article/details/7874817 #读取图片并存储为矩阵 from scipy.misc import imread im = ...