Range Sum Query - Immutable
Given an integer array nums, find the sum of the elements between indicesi andj (i ≤j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
class NumArray {
private:
vector<int> sums;
public:
NumArray(vector<int> nums) {
int sum=0;
for(int i=0;i<nums.size();i++)
{
sum += nums[i];
sums.push_back(sum);
}
}
int sumRange(int i, int j) {
return (sums[j]-sums[i-1]);
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
Counting Bits
Given a non negative integer number num. For every numbersi in the range0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return[0,1,1,2,1,2]
.
0000 0
-------------
0001 1
-------------
0010 1
0011 2
-------------
0100 1
0101 2
0110 2
0111 3
-------------
1000 1
1001 2
1010 2
1011 3
1100 2
1101 3
1110 3
1111 4
从1开始,遇到偶数时,其1的个数和该偶数除以2得到的数字的1的个数相同,遇到奇数时,其1的个数等于该奇数除以2得到的数字的1的个数再加1
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
for(int i=1;i<=num;i++)
{
int count=res[i/2]+i%2;
res.push_back(count);
}
return res;
}
};
Continuous Subarray Sum
Given a list of non-negative numbers and a targetinteger k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple ofk, that is, sums up to n*k where n is also aninteger.
Example 1:
Input: [23, 2, 4, 6, 7], k=6 Output: True Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
Example 2:
Input: [23, 2, 6, 4, 7], k=6 Output: True Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.
不断遍历获取不同的子数组之和并判断是否可以整除K,若整除即返回,若遍历完后都没有满足条件的就返回错误。要注意K=0时候的情况。
#include <vector>
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
vector<int> sums;
int sum=0;
for(int i=0;i<nums.size();i++)
{
sum += nums[i];
sums.push_back(sum);
}
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
if((k!=0&&(sums[j]-sums[i]+nums[i])%k==0)||(k==0&&(sums[j]-sums[i]+nums[i])==0))
return true;
}
}
return false;
}
};