leetcode 303----sizeof指的是指针的大小而不是数组的大小!

先说坑!:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. using namespace std;  
  3. void fun(int *P)  
  4. {  
  5.     cout<<"在函数中"<<sizeof(P)<<endl;  
  6. }  
  7. int main()  
  8. {  
  9.     int A[10];  
  10.     int* B=new int[10];  
  11.     cout<<"数组名"<<sizeof(A)<<endl;  
  12.     cout<<"指针"<<sizeof(B)<<endl;  
  13.     fun(A);  
  14. }  

结果输出:

数组名40
指针4
在函数中4

sizeof区别!!注意!!!出处:http://blog.csdn.net/kangroger/article/details/20653255


Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Subscribe to see which companies asked this question.


一下子不知道如何下手了,看网上说  可以先求出sum[i],前i个的和存储起来再相减!代码如下:

class NumArray {
public:
    int* sum;
    int size;
    NumArray(vector<int> nums) {
        size = nums.size();
        if (size == 0)
             return ;
        sum = new int[size];
        sum[0] = nums[0];
        for (int i = 1 ; i < size ; i ++)
            sum[i] = sum[i - 1] + nums[i];
    }
    
    int sumRange(int i, int j) {
        int length = sizeof(sum);
        if(size == 0 || i > size || j > size || i > j)
            return 0;
        if(i == 0)
            return sum[j];
        else
            return sum[j] - sum[i-1];
    }
};


/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */




还是踩了sizeof的坑~注意啊指的是指针大小而不是数组元素个数!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值