LeetCode系列Easy【2】 Algorithms - Array

来源:互联网 发布:淘宝怎么拍图片 编辑:程序博客网 时间:2024/06/08 14:58

26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

My solution:

class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        i = 0        while i <= len(nums)-2:            if nums[i] == nums[i+1]:                nums.pop(i)            else:                i = i + 1        return(len(nums))nums= [1,1,2,3,3,3,5,7]print(Solution().removeDuplicates(nums))

27. Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

class Solution(object):    def removeElement(self, nums, val):        """        :type nums: List[int]        :type val: int        :rtype: int        """        i = 0        while i < len(nums):            if nums[i] == val:                nums.pop(i)            else:                i = i + 1        return(len(nums))

66. Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

不明白

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]
]

My Solution:

class Solution(object):    def generate(self, numRows):        """        :type numRows: int        :rtype: List[List[int]]        """        if numRows == 0:             return(list())        pt = list(1 for ind in range (0, numRows))        for i in range(0, numRows):            pt[i] = list ( 1 for ind in range(0, i+1))            for j in range(0, i+1):                if j != 0 and j != i:                    pt[i][j] = pt[i-1][j-1] + pt[i-1][j]                else:                    pt[i][j] = 1        return (pt)

Reference Solution:
可用append减去初始赋值步骤:

class Solution:    # @return a list of lists of integers    def generate(self, numRows):        result = []        for i in xrange(numRows):            result.append([])            for j in xrange(i + 1):                if j in (0, i):                    result[i].append(1)                else:                    result[i].append(result[i - 1][j - 1] + result[i - 1][j])        return resultif __name__ == "__main__":    print Solution().generate(5)

119. Pascal’s Triangle II

The Same

157. Read N Characters Given Read4

# Time:  O(n)# Space: O(1)## The API: int read4(char *buf) reads 4 characters at a time from a file.# # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.# # By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.# # Note:# The read function will only be called once for each test case.## The read4 API is already defined for you.# @param buf, a list of characters# @return an integerdef read4(buf):    global file_content    i = 0    while i < len(file_content) and i < 4:        buf[i] = file_content[i]        i += 1    if len(file_content) > 4:        file_content = file_content[4:]    else:        file_content = ""    return iclass Solution(object):    def read(self, buf, n):        """        :type buf: Destination buffer (List[str])        :type n: Maximum number of characters to read (int)        :rtype: The number of characters read (int)        """        read_bytes = 0        buffer = [''] * 4        for i in xrange(n / 4 + 1):            size = read4(buffer)            if size:                buf[read_bytes:read_bytes+size] = buffer                read_bytes += size            else:                break        return min(read_bytes, n)if __name__ == "__main__":    global file_content    buf = ['' for _ in xrange(100)]    file_content = "a"    print buf[:Solution().read(buf, 9)]        file_content = "abcdefghijklmnop"    print buf[:Solution().read(buf, 9)]

Easy to understand

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

My Solution:

class Solution(object):    def majorityElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        nums_dic = dict()        for i in range(0, len(nums)):            string = str(nums[i])            if string in nums_dic.keys():                nums_dic[string] = nums_dic[string] + 1            else:                nums_dic[string] = 1        m = max(nums_dic.values())        for i in range(0,len(nums_dic)):             if nums_dic.values()[i] == m:                return (int(nums_dic.keys()[i]))

Sue list to save the appearance of every element in noms.
But this is slow.

class Solution:    # @param num, a list of integers    # @return an integer    def majorityElement(self, num):        idx, cnt = 0, 1        for i in xrange(1, len(num)):            if num[idx] == num[i]:                cnt += 1            else:                cnt -= 1                if cnt == 0:                    idx = i                    cnt = 1        return num[idx]if __name__ == "__main__":    print Solution().majorityElement([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6])

Since the majority element will appearance ,ore the n/2 times, this is a good idea to just use inc and cat to record.

189. Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

My Solution: (Wrong! Since it pop on original data, and nums= [ele]+nums creat a new list which is different from original one, see the example)
Reminder: void Do not return anything, modify nums in-place instead.

class Solution(object):    def rotate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: void Do not return anything, modify nums in-place instead.        """        n = len(nums)        if n != 0:            for i in range(0, k%n):                ele = nums.pop()                nums = [ele] + nums            print(nums)

Example:

A=[1,2,3]def test(a):    print(A)    print(a)    a.pop()    print(A)    print(a)    a=[3]+a    print(A)    print(a)

Correct Solution:
manipulate on the original list directly.

class Solution:    # @param nums, a list of integer    # @param k, num of steps    # @return nothing, please modify the nums list in-place.    def rotate(self, nums, k):        k %= len(nums)        self.reverse(nums, 0, len(nums))        self.reverse(nums, 0, k)        self.reverse(nums, k, len(nums))    def reverse(self, nums, start, end):        while start < end:            nums[start], nums[end-1] = nums[end-1], nums[start]            start += 1            end -= 1

243. Shortest Word Distance (Not Available)

293. Flip Game

396. Rotate Function

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a “rotation function” F on A as follow:

F(k) = 0 * Bk[0] + 1 * Bk[1] + … + (n-1) * Bk[n-1].

Calculate the maximum value of F(0), F(1), …, F(n-1).

Note:
n is guaranteed to be less than 105.

Example:

A = [4, 3, 2, 6]

F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

Top solution: Smart!(Reduce a lot of loop work)

class Solution(object):    def maxRotateFunction(self, A):        """        :type A: List[int]        :rtype: int        """        s = sum(A)        fi = 0        for i in xrange(len(A)):            fi += i * A[i]        result = fi        for i in xrange(1, len(A)+1):            fi += s - len(A) * A[-i]            result = max(result, fi)        return result

412. FizzBuzz

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,

Return:
[
“1”,
“2”,
“Fizz”,
“4”,
“Buzz”,
“Fizz”,
“7”,
“8”,
“Fizz”,
“Buzz”,
“11”,
“Fizz”,
“13”,
“14”,
“FizzBuzz”
]

Best Solution:

def fizzBuzz(self, n):    return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

414. Third Maximum Number

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:
Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

My Solution:

class Solution(object):    def thirdMax(self, nums):        """        :type nums: List[int]        :rtype: int        """        result = list(set(nums))        result.sort()        n = len(result)        if n >= 3:            return(result[n-3])        else:            return(result[n-1])

422. Valid Word Square

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]

Top Solution:

class Solution(object):    def findDisappearedNumbers(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        # For each number i in nums,        # we mark the number that i points as negative.        # Then we filter the list, get all the indexes        # who points to a positive number        for i in range(len(nums)):            index = abs(nums[i]) - 1            nums[index] = - abs(nums[index])        return [i + 1 for i in range(len(nums)) if nums[i] > 0]
0 0
原创粉丝点击