lintcode-Continuous Subarray Sum

题目

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone)


举例

Give [-3, 1, 3, -3, 4], return [1,4].


AC代码

class Solution {
public:
    /**
     * @param A an integer array
     * @return  A list of integers includes the index of 
     *          the first number and the index of the last number
     */
    vector<int> continuousSubarraySum(vector<int>& A) {
        // Write your code here
        //if (A.empty() || A.size() == 0) return null;
        int max = INT_MIN;
        int minpos = 0, maxpos = 0;
        int sum = 0;
        vector<int> ans;
        ans.push_back(0);
        ans.push_back(0);
        
        for (int i = 0; i < A.size(); i++) {
            if(sum < 0) {
                sum = A[i];
                minpos = maxpos = i;
            } else {
                sum += A[i];
                maxpos = i;
            }
            
            if (sum >= max) {
                max = sum;
                ans[0] = minpos;
                ans[1] = maxpos;
            }
        }
        return ans;
    }
};


思路

  1. 当sum 小于0时,则sum从下一个开始;
  2. sum大于等于0时,sum继续求和,maxpos向后移;
  3. 如果当sum大于max, 让max最大;
  4. 继续下一个元素。


总结
1.C++ 里找int型的最大数,最小数 ,可以用 #include<limit.h>
   MAX_INT, MIN_INT

2.vector里的迭代器

vector :: iterator t

t = A.begin();
//t不是那个元素,而是指向那个数的指针,所以如果用值,则是 *t
//要用到索引的是,最好A[i] ,A.at(i)

3.关于i++ 和 ++i
(1)如果只是看i++和++i,这两个是等价的,都等同于i=i+1,都是变量自身加1。
(2)在一般情况下,它们都是跟赋值联系在一起。
         比如:int a; a=i++;//将i的值赋值给a,即a=i;
         然后再执行i=i+1;
         也就是【a=i++;】与【a=i; i=i+1;】等价。
         a=++i;//将i+1的值赋给a,即a=i+1;
         然后再执行i=i+1;
         也就是【a=++i;】与【a=i+1;i=i+1;】等价。
(3)【总结一下】
       ①前置++是将自身加1的值赋值给新变量,同时自身也加1;
       ②后置++是将自身的值赋给新变量,然后才自身加1.


猜你喜欢

转载自blog.csdn.net/heheSakura/article/details/77433993
今日推荐