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.

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int sumNum = nums.size() * nums[0].size();
        int r1 = nums.size();
        int c1 = nums[0].size();
        if (sumNum != r*c) {
            return nums;
        }
        vector<vector<int>> result = vector<vector<int>>(r,vector<int>(c,0));
        int j = 0;
        for (int i =0; i<r*c; i++) {
            result[i/c][i%c] = nums[i/c1][i%c1];
        }
        
        return result;
    }
};
2017/11/29 posted in  leetcode

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.

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        
        if (nums.size()<2) {
            return nums.size();
        }
        unordered_map<int, int>startIndex , number;
        int len = nums.size();
        int fre = 0;
        for (int i=0; i<nums.size(); i++) {
            if (startIndex.count(nums[i])==0) {
                startIndex[nums[i]]=i;
            }
            number[nums[i]]++;
            if (number[nums[i]]==fre) {
                len = min(i-startIndex[nums[i]]+1, len);
            }
            if (number[nums[i]]>fre) {
                len = i - startIndex[nums[i]] + 1;
                fre = number[nums[i]];
            }
        }
        
        return len;
    }
};

该算法主要使用了两个hash_map:
一个来记录数字所出现的次数,另一个记录数字最开始出现的位置。一旦有一个数字的频数超过了当前的len,则更新len,若两个数字出现的频率相等则取长度最小的。

2017/11/23 posted in  leetcode

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.

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        
        if(nums.empty()) return -1;
        
        int sum = 0;
        for(int i=0;i<nums.size();i++) sum+=nums[i];
    
        int leftSum = 0;
        for(int j=0;j<nums.size();j++)
        {
            if (leftSum == sum - nums[j] -leftSum) {
                return j;
        }
            leftSum += nums[j];
        }
        
        return -1;
    }
};
2017/11/23 posted in  leetcode

Best Time to Buy and Sell Stock II

Say you have an array for which the \(i^{th}\) 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).

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

2017/11/23 posted in  leetcode

Best Time to Buy and Sell Stock

Say you have an array for which the \(i^{th}\) element is the price of a given stock on day i.

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

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice=INT_MAX;
        int maxProfit = 0;
        
        for (int i=0; i<prices.size(); i++) {
            minPrice = min(prices[i], minPrice);
            maxProfit = max(maxProfit, prices[i]-minPrice);
        }
        
        return maxProfit;
    }
};
2017/11/23 posted in  leetcode

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.

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        
        sort(nums.begin(),nums.end());
        int result=0;
        for (int i=0; i<nums.size(); i+=2) {
            result+=nums[i];
        }
        return result;
    }
};
2017/11/23 posted in  leetcode