文章目录
int main() { int arr[10] = { 2,34,6,67,33,47,56,567,1,4 }; heapsort(arr, 10); int max = 207; int n = 0, sum = 0; for (int i = 0; i < 10; i++) { if (sum > max) { break; } sum += arr[i]; n++; } printf("%d ", n); return 0; }
种花问题
```c int main() { int arr[5] = { 1,0,0,0,1 }; int n = 1; int i = 0; int count = 0; for (i = 0; i < 5; ) { if (arr[i] == 1)//遇到花就跳两格 { i += 2; } else if (arr[i - 1] == 1 && i > 0)//不是花,但是他前面有花且不是第一个,跳1格 { i += 1; } else if (arr[i + 1] == 1 && i+1<5)//不是花,但他后面有花,且不是最后一个,跳3格 { i += 3; } else//前后都没花 { arr[i] = 1; i += 2;//跳两格 count++; if (count == n) { printf("yes"); } } } return 0; }
小行星碰撞
2 <= asteroids.length <= 104 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0
/** * Note: The returned array must be malloced, assume caller calls free(). */ //正数往右走,负数往左走 #include<math.h> int* asteroidCollision(int* asteroids, int asteroidsSize, int* returnSize) { int n = 0; while (1) { int prev = 0; int next = 1; //每次都重左到右扫描一遍 while (next < asteroidsSize)// 每次只消一个,这个循环是把所有的都消掉,能够保证两者除0外都挨着 { if (asteroids[prev] * asteroids[next] < 0) { //1.背靠背不能碰撞 //如-9 8 32 9 //如-9 0 8 9//我们不能够让前后都往后走一步,因为0是有隐患的,我们不走0 //prev next // prev next //-9 0 8 9 if (asteroids[prev] < 0)//前面的往前走,后面的往后走就不符合 { prev = next; next++; //背靠背不能再碰了,就进入下一个循环 continue; } //发生了碰撞,左边大 if (abs(asteroids[prev]) > abs(asteroids[next])) { asteroids[next]=0; n++; } if (abs(asteroids[prev]) < abs(asteroids[next])) { asteroids[prev] = 0; n++; } if (abs(asteroids[prev]) == abs(asteroids[next])) { asteroids[next] = 0; asteroids[prev] = 0; n+=2; } break;//贪心不贪婪 } //如果前后相乘为0 //0 3,左边的等于0 if (asteroids[prev] == 0) { prev = next; next++; } //如果前后相乘为0 //3 0,右边的等于0 if (asteroids[next] == 0)//左边不动 { next++; } else { //prev next //7 0 0 4 -2 //方向相同,就前进一步 prev = next;//要跨过0 next++; } } //出来了,next就大于size了 if (next > asteroidsSize) { break; } } *returnSize = asteroidsSize - n;//返回剩余的 int *ret = (int *)malloc(sizeof(int)*(asteroidsSize - n)); int i,j=0; for (i = 0; i < asteroidsSize; i++) { if (asteroids[i]) { ret[j++] = asteroids[i]; } } return ret; }