Array - 121. 122. 152. 153. 154. 162. 167. 169. 189.

121Best Time to Buy and Sell Stock

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

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

提示:方法一:直接   保存最低价,每个元素减去这个最低价,max记录最大值。但是不适用于给的数据不是每天的价格而是相对于前一天的涨落。

方法二:Kadane's Algorithm 

答案:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxCur = 0, maxSoFar = 0;
        for(int i = 1; i < prices.size(); i++) {
            maxCur = max(0, maxCur += prices[i] - prices[i-1]);
            maxSoFar = max(maxCur, maxSoFar);
        }
        return maxSoFar;
    }
};

122Best 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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

提示:只要明天的价格比今天高,就加上 price[i + 1] - price[i]

答案:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;
        int total = 0;
        for (int i=0; i< prices.size()-1; i++) {
            if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];
        }
        return total;
    }
};
123Best Time to Buy and Sell Stock III

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 at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

提示:

答案:

152Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

提示:

1.imax/imin stores the max/min product of subarray that ends with the current number A[i]

2.multiplied by a negative makes big number smaller, small number bigger so we redefine the extremums by swapping them

答案:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if(nums.empty()) return INT_MIN;
        int res = nums[0], n = nums.size();
        for(int i = 1, imax = res, imin = res; i < n; i++){
            if(nums[i] < 0)  swap(imax, imin);
            imax = max(nums[i], imax * nums[i]);
            imin = min(nums[i], imin * nums[i]);
            res = max(res, imax);
        }
        return res;
    }
};

153Find Minimum in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

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

提示:方法一:二分查找

         方法二:一旦一个数比前一个数小就return这个数,最后return nums[0]

答案:

class Solution {
public:
    int findMin(vector<int>& nums) {
        int start = 0, end = nums.size() - 1;
        while(start < end){
            if(nums[start] < nums[end]) return nums[start];
            int mid = start + (end - start)/2;
            if(nums[mid] >= nums[start])
                start = mid + 1;
            else
                end = mid;
        }
        return nums[start];
    }
};
class Solution {
public:
    int findMin(vector<int>& nums) {
        for(int i = 0; i < nums.size() - 1; i++)
        {
            if(nums[i] > nums[i + 1])
                return nums[i + 1];
        }
        return nums[0];
    }
};

154Find Minimum in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

The array may contain duplicates.

Example 1:

Input: [1,3,5]
Output: 1

提示:方法一:比153多了一种if分支,如果nums[mid] == nums[r] 的情况

          方法二:同153方法二

答案:

int l = 0, r = nums.size() - 1;
		int mid;
		while (l <= r) {
			mid = l + (r - l) / 2;
			if (nums[mid] > nums[r]) l = mid + 1;
			else if (nums[mid] == nums[r]) {
				if (l == r) return nums[l];
				else r--;
			}
			else r = mid; // <
		}
		return nums[l];
class Solution {
public:
    int findMin(vector<int>& nums) {
        for(int i = 0; i < nums.size() - 1; i++)
        {
            if(nums[i] > nums[i + 1])
                return nums[i + 1];
        }
        return nums[0];
    }
};
162Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array nums, where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Note: Your solution should be in logarithmic complexity.

提示:方法一:二分查找

         方法二:算法时间复杂度为O(n)

答案:

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int low = 0, high = nums.size() - 1;
        while (low < high - 1) {
            int mid = (low + high) / 2;
            if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) 
                return mid;
            else if (nums[mid] > nums[mid + 1]) 
                    high = mid - 1;
                 else 
                    low = mid + 1;    
        }
        return nums[low] > nums[high] ? low : high;
    }
};

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
          for(int i = 1; i < nums.size(); i ++)
        {
            if(nums[i] < nums[i-1])
            {// <
                return i-1;
            }
        }
        return nums.size()-1;
    }
};
167Two 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.

Note:

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

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

提示:方法一:两根指针,long sum,注意坐标从1开始

          方法二:unordered_map不推荐

答案:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;  
        int start = 0, end = numbers.size() - 1;
        while(start < end){
            long sum = numbers[start] + numbers[end];
            if(target > sum)
                start++;
            else if(target < sum)
                end--;
            else{
                result.push_back(start + 1);
                result.push_back(end + 1);
                break;
            }
        }
        return result;
    }
};

169Majority 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.

Example 1:

Input: [3,2,3]
Output: 3

提示:方法一:Boyer-Moore Majority Vote Algorithm 仅用一个count

          方法二:排序

          其他方法

答案:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
         int major=nums[0], count = 1;
        for(int i=1; i<nums.size();i++){
            if(count==0){
                count++;
                major=nums[i];
            }else if(major==nums[i]){
                count++;
            }else count--; 
        }
        return major;
    }
};
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        return nums[nums.size()/2];
    }
};
189Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

提示:三个reverse

       其他方法

答案:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        reverse(nums.begin(),nums.end());
        reverse(nums.begin(),nums.begin()+k%n);
        reverse(nums.begin()+k%n,nums.end());
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值