本帖最后由 匿名 于 2023-9-29 21:09 编辑
leetcode 原题:
题目:
Given an array nums which consists of only '0's and '1's where '1' denotes there's a stone at a given position, an index p, and an integer k. Find the minimum steps needed to stack at least k stones at position p. Within one step, you're only allowed to move one stone to an adjacent position.
# nums: [1,0,1,0,0,1]
# k: 2
# p: 2
# result=2
Followup:# Given an array nums which consists of only '0's and '1's where '1' denotes there's a stone at given position, and an integer k. Find the minimum steps needed to stack at least k stones. Within one step, you're only allowed to move one stone to an adjacent position.
解题:
public static int move(int[] stones, int k, int p){
if(k <= 0)
return 0;
if(p >= stones.length)
return -1;
// int index = 0;
// for(int i=0; i <stones.length;i++){
// if(stones[i] == 1)
// stones[index++] = i;
// }
// if(index < k)
// return -1;
// int[] presum = new int[index];
// presum[0] = stones[0];
// for(int j=1;j < index;j++){
// presum[j] += presum[j-1] + stones[j];
// }
// int result = Integer.MAX_VALUE;
int remain = k - stones[p];
int steps = 0;
int l=p-1,r=p+1;
while(remain > 0){
if(l >=0 && stones[l] == 1 && remain > 0){
steps +=(p -l);
remain--;
}
if(stones[r] == 1 && r < stones.length && remain > 0){
steps += (r - p);
您好! 本帖隐藏的内容需要积分高于 188 才可浏览 您当前积分为 0。 使用VIP即刻解锁阅读权限或查看其他获取积分的方式 游客,您好! 本帖隐藏的内容需要积分高于 188 才可浏览 您当前积分为 0。 VIP即刻解锁阅读权限 或 查看其他获取积分的方式 blank">https://blog.csdn.net/qq_46105170/article/details/117814799
第三题:
有一个 linklist 5 - 3 - 2, - 4 - 1 - 8 - 2 - 1 - 3 - 4 - 6, 和 target 3 给出一个新的linklist 是由 小于 target 等于 target 大于 target 拼在一起
比如说 上面 output 就是 2 - 1 - 2 - 1 - 3 - 3 - 5 - 4 - 8 - 4 - 6
解题:定义三个临时头节点,然后while loop
sd题目:
补充内容 (2023-09-30 10:11 +08:00):
第一次排版有点乱。 |