leetcode -- 278、283

278.The first bad version

problem description

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version.

Solution methods

一看就知道是二分查找的题目,但是和之前的二分查找不一样,之前接触的二分查找是找某个元素,这次是查找某个分界点。因此代码也有区别,看了评论才明白的

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

int firstBadVersion(int n) 
{
    int left = 1, right = n, mid = left + (right - left) / 2;
    
    while (left < right)
    {
        mid = left + (right - left) / 2;
        if (isBadVersion(mid) == true)
            right = mid;
        else
            left = mid + 1;
    }  
    return left;
}

在这里插入图片描述

283.move zeroes

problem description

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:

  • You must do this in-place without making a copy of the array.
  • Minimize the total number of operations.

Solution Method

遍历一次,将所有的零覆盖掉,计算零的总数,之后再补在数组后面。

void moveZeroes(int* nums, int numsSize)
{
    int zeroCount = 0;      // 零的个数
    
    for (int i = 0; i < numsSize;  i++)
    {
        if (nums[i] != 0)       // 说明不是零, 往前移动
        {
            nums[i - zeroCount] = nums[i];
            continue;
        }
        zeroCount ++;                // 说明零
    }
    for (int i = numsSize - zeroCount; i < numsSize; i ++)      // 后面补零
        nums[i] = 0;
}

在这里插入图片描述

发布了184 篇原创文章 · 获赞 253 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/williamgavin/article/details/104570427