LeetCode--122、167、169、189、217 Array(Easy)

Posted on 2018-02-03 10:15  _hqc  阅读(144)  评论(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).

题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/

题意:给定每日股价,求若干次买卖所得最大利润

思路:求连续上升和

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        ans, n = 0, len(prices)
        for i in range(n-1):
            if prices[i+1] > prices[i]:
                ans += prices[i+1] - prices[i]
        return ans

 

167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

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

题目地址:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/

题意:给定一个人升序的数组和target,求出数组中和为target的两个数的位置

思路:hash

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i,n in enumerate(numbers):
            m = target - n
            if m in d:
                return(d[m]+1, i+1)
            else:
                d[n] = i

 

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.

题目地址:https://leetcode.com/problems/majority-element/description/

题意:给定长为n的数组,返回出现次数大于n/2的元素

思路:排序

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sorted(nums)[len(nums) / 2]

 

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

题目地址:https://leetcode.com/problems/rotate-array/description/

题意:将数组的后k个元素移到前面

思路:

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)
        k = k%n
        nums[:] = nums[n-k:] + nums[:n-k]

 

217. Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

题目地址:https://leetcode.com/problems/contains-duplicate/description/

题意:给定一个数组,判断是否有重复

思路:①排序 ②hash

排序

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        nums = sorted(nums)
        for i in range(len(nums)-1):
            if nums[i] == nums[i+1]:
                return True
        return False

hash

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        val = set()
        for n in nums:
            if n in val:
                return True
            else:
                val.add(n)
        return False