栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ leecode

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ leecode

从零开始刷leecode 704 二分查找


两种解法:左闭右闭,左闭右开。重点区间定义。
解法一

class Solution {
public:
    int search(vector& nums, int target) {
        int len = nums.size();
        int a = 0;
        int b = len-1;
        
        while (a<=b)  //左闭右闭
        {
            int m = a + ((b-a) / 2); //防止溢出
            if (nums[m] > target)
                b = m-1;
            else if (nums[m] < target)
                a = m+1;
            else
                return m;
        }
        return -1;
    }
};

解法二:

class Solution {
public:
    int search(vector& nums, int target) {
        int a = 0;
        int b = nums.size();
        
        while (a target)
                b = m; //右开无需加一
            else if (nums[m] < target)
                a = m+1;
            else
                return m;
        }
        return -1;
    }
};

##977

非递减数列,其平方最大值一定在左右两边上。

class Solution {
public:
    vector sortedSquares(vector& nums) {
        int i = 0;
        int j = nums.size()-1;
        int k = j;
        vector result(j+1, 0);
        while (i <= j){
            int ti = nums[i]*nums[i];
            int tj = nums[j]*nums[j];
            if (ti < tj){
                result[k--] = tj;
                j--;
            }
            else {
                result[k--] = ti;
                i++;
            }
        }
        
        return result;
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429840.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号