我在LeetCode上做二分搜索题。当我使用pivot++或pivot--时,自动分类器会显示“超过时间限制”,但如果我使用pivot+1或pivot-1,它会接受解决方案。有人知道为什么会发生这种情况吗?
附注:问题说明我的解必须有O(log )时间复杂度。
此代码不被接受:
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int pivot = 0;
while (left <= right) {
pivot = left+(right-left)/2;
if (nums[pivot] == target) return pivot;
if (nums[pivot] > target) right = pivot--;
else left = pivot++;
}
return -1;
}
}此代码被接受:
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int pivot = 0;
while (left <= right) {
pivot = left+(right-left)/2;
if (nums[pivot] == target) return pivot;
if (nums[pivot] > target) right = pivot-1;
else left = pivot+1;
}
return -1;
}
}发布于 2021-08-26 12:12:07
同样,pivot++将首先返回pivot的值,然后递增,pivot+1将返回递增的值,如果使用++pivot,它将首先递增pivot的值,然后返回新的递增的值
发布于 2021-08-26 12:18:05
int x = 5;
int y = x++; //assigns x to y and then increments x, so y = 5, x = 6;
int z = ++x; //increments x and then assigns its value to y, so y = 7, z = 7;
int e = z + 1; //adds 1 to z and assigns result to e, but doesn't change z, so e = 8, z = 7.https://stackoverflow.com/questions/68936962
复制相似问题