leetcode array problems 1252, 1304, 121

1252. Cells with Odd Values in a Matrix

Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

Return the number of cells with odd values in the matrix after applying the increment to all indices.

Constraints:

  • 1 <= n <= 50
  • 1 <= m <= 50
  • 1 <= indices.length <= 100
  • 0 <= indices[i][0] < n
  • 0 <= indices[i][1] < m

Example 1:

Input: n = 2, m = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.

Solutions:

class Solution {
public:
    int oddCells(int n, int m, vector<vector<int>>& indices) {
        int a[n][m]; int count = 0;
        for(int i = 0; i < n; i++)     //First Error: no initialization
            for(int j = 0; j < m; j++)
                a[i][j] = 0;
        
        for(int i = 0; i < indices.size(); i++)
            for(int j = 0; j < indices[i].size(); j++)
            {
                if(j == 0)
                    for(int k = 0; k < m; k++)
                       a[indices[i][j]][k] += 1;
                else
                    for(int k = 0; k < n; k++) //Second Error: stack buffer overflow (k < m)
                       a[k][indices[i][j]] += 1;
            }
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(a[i][j]%2 == 1)
                    count++;
        
        return count;
    }
};

Performance:

Useful Knowlege:

C++中创建二维数组的四种方法

C/C++语言二维数组的传参方法总结

 

1304. Find N Unique Integers Sum up to Zero

Given an integer n, return any array containing n unique integers such that they add up to 0.

Constraints:

  • 1 <= n <= 1000

Example 1:

Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Solutions:

class Solution {
public:
    vector<int> sumZero(int n) {
        vector<int> a;
        set<int> s;
        int t;

        for(int i = 0; i < n/2; i++)
        {
            t = rand()%1000 + 1;
            while(s.find(t) != s.end())  //guarantee to generate unique numbers
            {
                t = rand()%1000 + 1;
            }
            s.insert(t);
            a.push_back(t);
        }
        
        if(n%2 == 1)
            a.push_back(0);
        
        for(int i = 0; i < n/2; i++)
        {
            a.push_back(-a[i]);
        }
        
    return a;
    }
};

Performance:

The reason of Runtime Error:

vector<int> a;
a[n/2] = 0;   //assign a new value to a[n/2] without initializing vector a

Useful Knowlege:

vector去重方法

C++产生随机数

C++中set用法详解

 

121. Best 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.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Time Limit Exceeded Answer:

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

 

(Unsolved ) produce the right answer on local IDE(DevC++) but get a wrong answer on the Leetcode website based on the same test case.

Reflection: The reason why I write so complex code block is that I stuck with the wrong thought that there might exist a difference between the two numbers(not include the maximum or minimum of the prices array) that larger than the difference between prices on any day and the minimum of the prices. The latter is the right way to calculate the max profit.

Wrong Answer:

class Solution {
public:
   int maxProfit(vector<int>& prices) {
       int psize = prices.size();
       int maxprofit = 0; 
       int num = 20;
       vector<vector<int> > map;

       for(int i=0; i < num; i++) 
           map.push_back(vector<int>());
       
       vector<int> count;
       for(int i=0; i < num; i++)
           count.push_back(0);

       for(int i=0; i < psize; i++)
       {
       	    if(map[prices[i]].size()>=1)
                count[prices[i]]++;
           map[prices[i]].push_back(i);
       }

        sort(prices.begin(), prices.end());
      
        
        for(int i=0; i < psize-1; i++)
        {
            for(int j = psize-1; j > i; j--)   
            {

                if(map[prices[j]][count[prices[j]]] > map[prices[i]][count[prices[i]]] && (prices[j]-prices[i]) > maxprofit)
                {
                    maxprofit = prices[j]-prices[i]; break;
                }
            }
               
        }
        
       return maxprofit;
    }
};

Final Answer:

class Solution {
public:
   int maxProfit(vector<int>& prices) {  
       int minprice = INT_MAX;     //INT_MAX = 2^31-1,INT_MIN= -2^31
       int maxprofit = 0;
       for(int i=0; i < prices.size();i++)  //one pass
       {
           if(prices[i] < minprice)
               minprice = prices[i];
           else if (prices[i]-minprice > maxprofit)
               maxprofit = prices[i]-minprice;
       }

       return maxprofit;
    }
};

Performance:

Useful Knowlege:

C++数组或vector求最大值最小值

C++ vector的用法

C++ STL中sort()原理浅解

C++_vector操作

C++ map用法总结(整理)

C/C++整型上下限INT_MAX INT_MIN及其运算

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值