python算法题day1

来源:互联网 发布:java电子书 编辑:程序博客网 时间:2024/06/07 22:05

欢迎使用Markdown编辑器写博客


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).
感觉应该是先排序,然后按照从小到大的顺序,两个一组,这样的和最大

class Solution(object):    def arrayPairSum(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums)==0 and (len(nums)/2)>10000:            return 0        sum,i=0,0        nums.sort()        while i < len(nums):            sum+=nums[i]            i+=2        return sum

!最开始很快写完了,然后状态显示为?,不是所有测试数据都通过了,然后加了最开始的判断,return 0的,才通过了。。。。。终于是做完了第一个题

485. Max Consecutive Ones

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
找到该数组中连续1的最大数。

class Solution(object):    def findMaxConsecutiveOnes(self, nums):        """        :type nums: List[int]        :rtype: int        """        count=[0]        n=0        if len(nums)>10000 and len(nums)==0:            return 0        for i in nums:            if i not in range(2):                return 0            if i == 1:                n+=1            else:                n=0            count.append(n)        return max(count)

566. Reshape the Matrix

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.

最开始对于矩阵的行列不太清楚,去查了,python的矩阵方法

import numpy as npx = np.array([[1,2,5],[2,3,5],[3,4,5],[2,3,6]])# 输出数组的行和列数print x.shape  # (4, 3)# 只输出行数print x.shape[0] # 4# 只输出列数print x.shape[1] # 3后来看到,len(x)  len(x[0])  不就好啦import numpy as np  class Solution(object):      def matrixReshpe(self, num, r, c):           try:               return np.reshape(num, (r, c)).tolist()          except:              return numsclass Solution(object):    def matrixReshape(self, nums, r, c):        """        :type nums: List[List[int]]        :type r: int        :type c: int        :rtype: List[List[int]]        """        m=len(nums)        n=len(nums[0])        if m not in range(1,101) or n not in range(1,101) or r<0 or c<0:            return 0        if m*n != r*c:            return nums        else:            temp=[num for row in nums for num in row]            newMatrix = [[0 for j in xrange(c)] for i in xrange(r)]              for i in xrange(r):                 for j in xrange(c):                      newMatrix[i][j]=temp[i*c+j]            return newMarix class Solution(object):    def matrixReshape(self, nums, r, c):        """        :type nums: List[List[int]]        :type r: int        :type c: int        :rtype: List[List[int]]        """        m=len(nums)        n=len(nums[0])        new=[]        if m not in range(1,101) or n not in range(1,101) or r<0 or c<0:            return 0        if m*n != r*c:            return nums        else:            temp=[num for row in nums for num in row]            newMatrix = [[0 for j in xrange(c)] for i in xrange(r)]              for i in xrange(r):                 for j in xrange(c):                      newMatrix[i][j]=temp[i*c+j]            new=newMatrix            return new

这个里面,关于数组的表示需要关注,[num for row in nums for num in row]展成一列。最开始一直编译不过,后来,我重新设了个变量,然后就过了,不知道为什么。

448. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

class Solution(object):    def findDisappearedNumbers(self, nums):        return list(i for i in range(1, len(nums) + 1) if i not in nums)

283. Move Zeroes

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.        """        y = 0        for x in range(len(nums)):            if nums[x]:                nums[x], nums[y] = nums[y], nums[x]                y += 1

怎么快速去掉0

122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/

https://segmentfault.com/a/1190000002565570

这里写代码片

167. Two Sum II - Input array is sorted

注意题目说了两个重要条件:1,有序数组; 2,有唯一解所以解的两个数一定都是数组中唯一存在的数。

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路一

利用两个指针从数组的两侧开始向中间移动,寻找第一对和为目标的两个数即为所求。

这里写代码片

思路二

扫描数组,用字典记录扫描历史,并判断可能成对的另一个数是否在数组中。

这里写代码片
原创粉丝点击