Array - 81. 88. 90. 105. 106. 118. 119. 120.

81Search in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

提示:与I的区别是允许数组中有重复,用while语句去除左右重复

答案:

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        if(nums.empty())  return false;   
        int start = 0, end = nums.size() - 1;  
        while(start <= end){  
            while (start < end && nums[start] == nums[start + 1]) start++; // skip duplicates from the left
            while (end > start && nums[end] == nums[end - 1]) end--; // skip duplicates from the right
            int mid = (start + end)/2;  
            if(nums[mid] == target ) return true;
            if(nums[mid] < nums[end]){// eg. 5,6,1,2,3,4  
                if(target > nums[mid] && target <= nums[end]){   
                    start = mid + 1;  
                }else{  
                    end = mid - 1;  
                }  
            }else{// eg. 3,4,5,6,1,2  
                if(target > nums[mid] || target <= nums[end]){  
                    start = mid + 1;  
                }else{  
                     end = mid - 1;  
                }     
            }  
        }   
        return false;  
    }
};

88Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]

提示:由于是排序数组并且第一个数组足够大,那么从m+n-1开始赋值

答案:

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m - 1, j = n - 1, tar = m + n - 1;
        while (j >= 0) {
            nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
        }
    }
};

90Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

提示:排序,idx记录插入位置,sz保存大小。保证重复的元素只插入 上一过程中新添加的 元素,避免产生重复

答案:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> res(1,vector<int>());
        int sz = 0, n = nums.size();
        for(int i = 0; i < n; i++){
            int idx = (i >= 1 && nums[i] == nums[i - 1])? sz: 0;
            sz = res.size();
            for(int j = idx; j < sz; j++){
                res.push_back(res[j]);
                res.back().push_back(nums[i]);
            }
        }
        return res;
    }
};

105Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

提示:让我解释一下递归中的坐标。很简单的是,我们能看出来根据pos指向的根结点把 中序遍历分为两部分,[is, pos-1]与[pos+1,ie]。其中第一部分有 pos - is个元素,第二部分有 ie-(pos +1)+1个元素。对应的,先序遍历中 [ps+1,ps+pos - is]区间的元素属于左子树,[pe - (ie - (pos +1)+1)+1,pe]区间的元素属于右子树。

答案:

TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    return create(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}

TreeNode* create(vector<int>& preorder, vector<int>& inorder, int ps, int pe, int is, int ie){
    if(ps > pe){
        return nullptr;
    }
    TreeNode* node = new TreeNode(preorder[ps]);
    int pos;
    for(int i = is; i <= ie; i++){
        if(inorder[i] == node->val){
            pos = i;
            break;
        }
    }
    node->left = create(preorder, inorder, ps + 1, ps + pos - is, is, pos - 1);
    node->right = create(preorder, inorder, pe - ie + pos + 1, pe, pos + 1, ie);
    return node;
}

106Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

提示:参考105,新根结点为posterorder[pe],然后确定递归中的坐标

答案:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    TreeNode* create(vector<int>& inorder, vector<int>& postorder, int is, int ie, int ps, int pe){
        if(ps > pe) return nullptr;
        TreeNode* node = new TreeNode(postorder[pe]);
        int pos = 0;
        for(int i = is; i <= ie; i++){
            if(inorder[i] == node->val ){
                pos = i;
                break;
            }
        }
        node->left = create(inorder, postorder, is, pos - 1, ps, ps + pos - is - 1);
        node->right = create(inorder, postorder, pos + 1, ie, pe - ie + pos, pe - 1);
        return node;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return create(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    }
};

118Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

提示:resize()

答案:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> r(numRows);
        for(int i = 0; i < numRows; i++){
            r[i].resize(i + 1);
            r[i][0] = r[i][i] = 1;
            for(int j = 1; j < i; j++)
                r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
        }
        return r;
    }
};

119Pascal's Triangle II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

提示:i从1到rowIndex,j从i到1

答案:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> A(rowIndex + 1, 0);
        A[0] = 1;
        for(int i = 1; i < rowIndex + 1; i++)
            for(int j = i; j >= 1; j--)
                A[j] += A[j - 1];
        return A;
    }
};

120.Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:

Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

提示:mini保存三角最后一行,从下到上依次计算,返回mini[0]

答案:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if(triangle.empty()) return 0;
        vector<int> mini = triangle.back(); //让mini等于其最后一行
        for(int i = triangle.size() - 2; i >= 0; i--)
            for(int j = 0; j <= i; j++)
                mini[j] = triangle[i][j] + min(mini[j], mini[j + 1]);
        return mini[0];
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值