六月集训第一日

题目描述:

1588. 所有奇数长度子数组的和 - 力扣(LeetCode)

给你一个正整数数组 arr ,请你计算所有可能的奇数长度子数组的和

子数组 定义为原数组中的一个连续子序列

请你返回 arr所有奇数长度子数组的和

我的题解:
int sumOddLengthSubarrays(int* arr, int arrSize){
 int count=0;
 int i,j;
 for(i=0;i<arrSize;++i){//(1)   
     for(j=1;i+j<=arrSize;j+=2){
        // (2)
        int last=i+j-1;//(3)
        for(int k=i;k<=last;++k){
            //(4)
            count+=arr[k];
        }
     }
 }
 return count;
}
题解思路:
暴力:
    只会暴力太水了呜呜呜
(1)有奇数+偶数=奇数可将j放入其中
(2)j表示长度
(3)表示i到last保持长度位奇数
(4)最后再来个循环加起来

题目描述:

1848. 到目标元素的最小距离 - 力扣(LeetCode)

给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 targetstart ,请你找出一个下标 i ,满足 nums[i] == target 且 abs(i - start) 最小化 。注意:abs(x) 表示 x 的绝对值。

返回 abs(i - start)

题目数据保证 target 存在于 nums 中。。

我的题解:
int getMinDistance(int* nums, int numsSize, int target, int start){
    //以start开始往左右两边找
    if(nums[start]==target){
        return 0;
    }
    int right;
    int left;
    int count1=10000;
    int count2=10000;
    for(right=start+1;right<numsSize;right++){
        if(count1<10000)
            break;
        if(nums[right]==target){
            count1=abs(right-start);
            
        }
    }
    for(left=start-1;left>=0;left--){
        if(count2<10000)
          break;
        if(nums[left]==target){
            count2=abs(left-start);

        }
    }
    return count2>count1?count1:count2;
}
题解思路:
暴力:
从target开始分别往左右两边遍历就行蛮简单的

在这里插入图片描述

题目描述:

1652. 拆炸弹 - 力扣(LeetCode)

你有一个炸弹需要拆除,时间紧迫!你的情报员会给你一个长度为 n 的 循环 数组 code 以及一个密钥 k 。

为了获得正确的密码,你需要替换掉每一个数字。所有数字会 同时 被替换。

如果 k > 0 ,将第 i 个数字用 接下来 k 个数字之和替换。
如果 k < 0 ,将第 i 个数字用 之前 k 个数字之和替换。
如果 k == 0 ,将第 i 个数字用 0 替换。
由于 code 是循环的, code[n-1] 下一个元素是 code[0] ,且 code[0] 前一个元素是 code[n-1] 。

给你 循环 数组 code 和整数密钥 k ,请你返回解密后的结果来拆除炸弹!

我的题解:
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* decrypt(int* code, int codeSize, int k, int* returnSize){
    *returnSize=codeSize;
    int i,j;
    int* nums=(int*)malloc(sizeof(int)*codeSize);
    memset(nums,0,sizeof(int)*codeSize);
    if(k==0)
        return nums;
    if(k>0){
        for(i=0;i<codeSize;++i){
            int count=1;
            int sum=0;
            int j=i+1;
            while(count<=k){
                j%=codeSize;//避免出边界模拟循环
                sum+=code[j++];
                count++;
            }
            nums[i]=sum;
        }
    }else{
//小于0的情况
        k=-k;
        for(i=0;i<codeSize;++i){
            int sum=0,count=1;
            j=i-1;
            while(count<=k){
                if(j<0)
                    j+=codeSize;
                sum+=code[j--];
                count++;
            }
            nums[i]=sum;
        }
    }
    return nums;
}
我的思路:
就是分类讨论k》0和k《0的情况分开讨论,如果正超出的模运算,如果为负数直接加上数组大小即可

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值