暑假算法7.4,Day03
第一题
class NumArray {
int[] sum;
public NumArray(int[] nums) {
int length=nums.length;
sum=new int[length+5];
for(int i=0;i<length;i++){
sum[i+1]=sum[i]+nums[i];
}
}
public int sumRange(int left, int right) {
return sum[right+1]-sum[left];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
第二题
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
int ans = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j <= arr.length; j += 2) {
if (i + j - 1 < arr.length) {
for (int k = 0; k < j; k++) {
ans += arr[i + k];
}
}
}
}
return ans;
}
}
第三题
[和相同的二元子数组]( https://leetcode.cn/problems/binary-subarrays-with-sum/)
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int[] count = new int[nums.length + 10];
int res = 0;
int sum = 0;
for (int i=0;i<nums.length;i++) {
count[sum]++;
sum += nums[i];
if (sum - goal >= 0) {
res += count[sum - goal];
}
}
return res;
}
}
第四题
题目描述:有一把铲子卖k元,商店里有无数把这种铲子,你有无数个10元的硬币,但面值为r的硬币你只有1个(1<=r<=9),请问你最少要买多少把铲子,商家才不需要给你找零。
可以根据对10求余的余数来判断:
1.余数等于给的面值r
2.余数等于0;
#include<bits/stdc++.h>
using namespace std;
int x,y;
void dfs(int k)
{
int sum=x*k;
if (sum%10==y||sum%10==0)
{
cout<<k;
return;
}
else
{
dfs(k+1);
}
}
int main()
{
cin>>x>>y;
dfs(1);
return 0;
}