2017.10.19 LeetCode 二分 -> 69. Sqrt(x) -> 410. Split Array Largest Sum

来源:互联网 发布:求抢票软件 编辑:程序博客网 时间:2024/06/06 13:05

69. Sqrt(x)

Description

Implement int sqrt(int x).

Compute and return the square root of x.

题意:让你求x
分析: 直接二分即可,注意好边界条件即可

class Solution {public:    bool check(int x,int mid){        if(mid*1ll*mid <= 1ll*x){            return true;        }        return false;    }    int mySqrt(int x) {        int l = 0,r = x,ans,mid;        while(l <= r){            mid = l + r >> 1;            if(check(x,mid)){                ans = mid;                l = mid + 1;            }            else {                r = mid - 1;            }        }        return ans;    }};

410. Split Array Largest Sum

Description

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Note:

If n is the length of array, assume the following constraints are satisfied:

1 ≤ n ≤ 1000
1 ≤ m ≤ min(50, n)
Examples:

Input:

nums = [7,2,5,10,8]
m = 2

Output:

18

Explanation:

There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.

题意: 给你一个数组,和一个m,让你把这个数组分成连续的m块(非空),让你求每一块的和的最小值(有点拗口)范围:1n1000 1mmin(50,n)
分析:先把题意搞懂把,什么叫每一块和的最小值呢,简单的说就是分好后,计算每一块的sum,然后在所有块中取一个最大的sum,就是题目要找的,看似毫无头绪的题,细心发现其实是有规律的,大家都知道二分呢只要满足单调性和可判定性就可以使用啦,我们先找单调性,先看样例上的答案 18,为什么17不行呢,先带入下,如果答案是17的话,先是前三个[7, 2, 5],然后再是[10],再是[8],我们发现他是分了三块了,而要求为两块,显然不符合,这就是我们要找的单调性,我们发现,我们随着这个答案的变大,分的块数是变少的,这里呢单调性搞定了,在找判定性,也很好找,以为题目上给了m,直接比较即可,这时我们就可以放心大胆地使用二分了,当然啦还得注意一些地方,比如:是否会爆int,边界问题,等等,这些自己体会吧.

参考函数

class Solution {public:    bool check(vector<int> &nums,long long mid,int m) {        long long sum = 0;        int len = nums.size(),t = 0;        for(int i = 0;i < len;i++) {            if(sum + nums[i] > mid) {                t++;                sum = nums[i];                if(sum > mid) return false;            }else {                 sum += nums[i];            }        }        if(t+1 <= m)            return true;        return false;    }    int splitArray(vector<int>& nums, int m) {        long long sum = 0;        int len = nums.size();        for(int i = 0;i < len;i++) {            sum += 1ll*nums[i];                    }        long long  l = 0,r = sum,mid,ans;        while(l <= r){            mid = r + l >>1;            if(check(nums,mid,m)) {                ans = mid;                r = mid-1;            }else {                l = mid+1;            }        }        return (int)ans;            }};
原创粉丝点击