
三天学习完数组相关内容并总结
使用语言:C#
使用编译器:Visual Studio
- 1.长度最小子数组
- 2.乘积小于K的子数组
学习产出:
- 长度最小子数组
输入:正数数组和一个目标值
产出:返回找到长度最小子数组的长度或者返回0
public static int MinLen()
{
int[] nums = new int[] { 2, 3, 1, 2, 4, 3 };
int target = 7;
int sum = 0;
int minLen = 0;
int result = nums.Length + 1; //开始之前,给长度最小的子数组赋值(数组长度+1)
int i = 0; //记录滑动窗口的起始位置
for(int j = 0; j < nums.Length; j++)
{
sum += nums[j];
while (sum >= target)
{
minLen = j - i + 1;
result = result < minLen ? result : minLen;
sum -= nums[i++];//先从sum中减去num[i],再i++窗口左侧向右滑动一格
}
}
return result == nums.Length + 1 ? 0 : result; //
}
- 乘积小于K的子数组
输入:数组nums,目标值K
产出:满足乘积小于K的子数组的个数或者返回0
public static int ProLen()
{
int[] nums = new int[] { 10, 5, 2, 6 };
int k = 100;
int numsSize = nums.Length, result = 0;
for (int right = 0; right < numsSize; right++)
{//子数组以nums[right]为结尾
int left = right, tempK = 1;
while (left >= 0 && nums[left] * tempK < k)
{//left从right位置往前扩展子数组,直到超出数组左边界或者大小超过了K
tempK *= nums[left--];
result += 1;
}
}
return result;
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)