LeetCode Notebook 2020-2021
  • 序
  • 目录
  • 线性表
    • 数组
      • Remove Duplicates from Sorted Array
      • Remove Duplicates from Sorted Array II
      • Exercises I
      • Search in Rotated Sorted Array
      • Search in Rotated Sorted Array II
      • Median of Two Sorted Arrays
      • Longest Consecutive Sequence
      • Exercises II
      • Two Sum
      • 3Sum
      • 3Sum Closest
      • 4Sum
      • Exercises III
      • Next Permutation
      • Permutation Sequence
      • Exercises IV
      • Valid Sudoku
      • Trapping Rain Water
      • Rotate Image
      • Plus One
      • Exercises V
      • Climbing Stairs
      • Set Matrix Zeroes
      • Gray Code
      • Gas Station
      • Exercises VI
      • Candy
      • Single Number
      • Single Number II
      • Exercises VII
    • 链表
      • Add Two Numbers
      • Reverse Linked List II
      • Partition List
      • Swap-nodes-in-pairs
  • 字符串
    • 字符串
      • Valid Palindrome
      • Implement strStr()
      • String to Integer(atoi)
      • Add Binary
      • Longest Palindromic Substring
      • Longest Common Subsequence
      • Regular Expression Matching
      • Rearrange Spaces Between Words
      • Longest Common Prefix
      • Wildcard Matching
      • subdomain visit count
  • 栈和队列
    • 栈
      • Min Stack
      • Valid Parentheses
    • 队列
  • 树
    • 二叉树的遍历
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Postorder Traversal
      • Search in a Binary Search Tree
    • 二叉树的构造
      • Untitled
    • 二叉查找树
      • Validate Binary Search Tree
    • 二叉树的递归
      • Untitled
  • 图
    • 图
  • 排序
    • 排序
      • Merge Sorted Array
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
      • Exercises I
      • Insertion Sort List
      • Sort List
      • Sort Color
      • First Missing Positive
      • Exercises II
  • 查找
    • 查找
      • Random Pick with Weight
      • Prefix and Suffix Search
      • Search Insert Position
      • Search a 2D Matrix
  • BFS
    • BFS
  • DFS
    • DFS
      • Split a String Into the Max Number of Unique Substrings
      • Palindrome Partitioning
      • Unique Path
      • Unique Path II
  • 动态规划
    • DP
      • Coin Change
      • Maximal Rectangle
      • Super Egg Drop
      • Exercises
      • Best Team With No Conflicts
  • 分治法
    • Divide And Conquer
  • 贪心法
    • Greedy
      • Jump Game
      • Jump Game II
      • Best time to buy and sell stock
      • Best time to buy and sell stock II
      • Container with most water
      • Exercises
  • 暴力枚举
    • Brute Force
      • Subsets
      • Subsets II
      • Permutation
      • Permutation II
      • Combinations
      • Letter Combinations of a Phone Number
  • others
    • 小岛题
    • 滑动窗口
      • Longest substring without repeating characters
      • Sliding Window Maximum
      • Max Consecutive One III
      • Count Number of Nice Subarrays
    • Roman number code
    • Untitled
由 GitBook 提供支持
在本页
  • Search Insert Position
  • First Bad Version
  • Find First and Last Position of Element in Sorted Array
  • Sum of Mutated Array Closest to Target
  • Find Minimum in Rotated Sorted Array
  • Find Minimum in Rotated Sorted Array II

这有帮助吗?

  1. 线性表
  2. 数组

Exercises II

Easy: 2; Medium: 3; Hard: 1

上一页Longest Consecutive Sequence下一页Two Sum

最后更新于4年前

这有帮助吗?

Search Insert Position

原题链接:

难度: easy

参考解法:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int i=0,site=0;
        while(i<nums.size()){
            if(nums[i]<target) site++;
            i++;
        }
        return site;
    }
};

Binary Search

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int min=0;
        int max=nums.size()-1;
        
        if (target<nums[min]) {return min;}
        else if(target>nums[max]) {return max+1;}
        else{
            while(min<=max){
                int mid=min + (max-min)/2;
                if(target<=nums[mid]) {max=mid-1; }
                else {min=mid+1;}
            }
            return min;
        }
    }
};

First Bad Version

难度:easy

参考解答:

Linear search 超时

class Solution {
public:
    int firstBadVersion(int n) {
        int i=0;
        while(i<n){
            if(isBadVersion(i)) break;
            i++;
        }
        return i;
    }
};

Binary search Accepted

class Solution {
public:
    int firstBadVersion(int n) {
        int min=1;
        int max=n;
        while(min<max){
            int mid=min+(max-min)/2;
            if(isBadVersion(mid)){max=mid;}
            else{min=mid+1;}
        }
        return min;
    }
};

Find First and Last Position of Element in Sorted Array

难度:medium

参考解答:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
    int idx1 = lower_bound(nums, target);
    int idx2 = lower_bound(nums, target+1)-1;
    if (idx1 < nums.size() && nums[idx1] == target)
        return {idx1, idx2};
    else
        return {-1, -1};
    }
    
    int lower_bound(vector<int>& nums, int target) {
        int l = 0, r = nums.size()-1;
        while (l <= r) {
            int mid = (r-l)/2+l;
            if (nums[mid] < target)
                l = mid+1;
            else
                r = mid-1;
        }
        return l;
    }
};

Sum of Mutated Array Closest to Target

难度:medium

题意分析:给定一个数组arr和一个整数target。

给出一个数值value,使其满足在arr中比value大的值改成value之后,arr中数的总和最接近target。

这个value可以是不是数组中的数。

Input: arr = [4,9,3], target = 10

Output: 3

Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.

Input: arr = [2,3,5], target = 10

Output: 5

Input: arr = [60864,25176,27249,21296,20204], target = 56803

Output: 11361

提示:ternary search/binary search

class Solution {
public:
    int findBestValue(vector<int>& A, int target) {
        sort(A.begin(), A.end());
        int n = A.size(), i = 0;
        while (i < n && target > A[i] * (n - i))
            target -= A[i++];
        return i == n ? A[n - 1] : int(round((target - 0.0001) / (n - i)));
    }
};

Returns the integral value that is nearest to x, with halfway cases rounded away from zero.

class Solution {
public:
    int findBestValue(vector<int>& arr, int target) {
        int l, r, mi, s=0, m=-1;
        for(int v:arr) s += v, m=max(m,v);
        
        if(s<=target) return m; // return the max value since we will keep all nums as is

        for(l=1,r=m;l<r;) {
            mi=(l+r)/2;
            s=0;
            for(int v:arr) s += (v>mi)?mi:v;
            if(s>=target) r=mi;
            else          l=mi+1;
        }
        // check if we are 1 step off the target 
        int s1=0,s2=0;
        for(int v:arr) s1 += (v>l)?(l):v, s2 += (v>l-1)?(l-1):v;
        
        return (abs(s2-target) <= abs(s1-target)) ? l-1 : l;
    }
};

Find Minimum in Rotated Sorted Array

难度:medium

参考解法:

class Solution {
public:
    int findMin(vector<int>& nums) {
        int res=INT_MAX;
        for(int n:nums) res=min(n,res);
        return res;
    }
};

Find Minimum in Rotated Sorted Array II

难度:hard

参考解法:

原题链接:

原题链接:

原题链接:

:

:

原题链接:

原题链接:

https://leetcode.com/problems/search-insert-position/
https://leetcode.com/problems/first-bad-version/
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/
参考解法
Round函数
Binary Search解法
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/