leetcode 题解代码整理 31-35题

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

给出一串数字序列,将其改变成字典序中下一个序列

在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列了。

class Solution
{
public:
    void nextPermutation(vector<int>& nums)
    {
        int len=nums.size();
        int mark;
        if (len<=1) return ;
        int i;
        for (i=len-1;i>0;i--)
        {
            if (nums[i]>nums[i-1])
            {
                mark=i;
                break;
            }
        }
        if (i==0)
        {
            for (i=0;i<len/2;i++)
            swap(nums[i],nums[len-i-1]);
            return ;
        }
        for (i=len-1;i>mark;i--)
        if (nums[i]>nums[mark-1]) break;

        swap(nums[i],nums[mark-1]);

        for (i=mark;i<len && i<(mark+len)/2;i++)
        swap(nums[i],nums[len-1+mark-i]);

    }
};

Longest Valid Parentheses

Given a string containing just the characters ‘(‘ and ‘)‘,
find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()",
which has length = 2.

Another example is ")()())", where the longest valid parentheses substring
is "()()", which has length = 4.

输出最长连续完全匹配括号的字符串长度

首先对字符串进行预处理,标记所有可以进行匹配的字符,然后找最长的可匹配子序列即可

class Solution
{
public:
    int longestValidParentheses(string s)
    {
        int len=s.length();
        bool *a=new bool[len];
        memset(a,false,len);
        stack<int>st;

        for (int i=0;i<len;i++)
        if (s[i]=='(')
            st.push(i);
        else
        {
            if (!st.empty())
            {
                a[st.top()]=true;
                a[i]=true;
                st.pop();
            }
        }

        int ans=0,cnt=0;;
        for (int i=0;i<len;i++)
        {
            if (a[i]==true) cnt++;
            else cnt=0;
            ans=max(ans,cnt);
        }

        return ans;
    }
};

Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4
5 6 7 0 1 2
).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

在一串有循环递增数组中找到指定值

在二分中间判断一下target属于左区间还是右区间即可

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

Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,

Given [5, 7, 7, 8, 8, 10] and target value 8,

return [3, 4].

输出查找数字所在范围

两个二分分别查找数字出现的最左端和最右端即可

class Solution
{
public:
    vector<int> searchRange(vector<int>& nums, int target)
    {
        vector<int>ans;
        int len=nums.size();
        if (len==0)
        {
            ans.push_back(-1);
            ans.push_back(-1);
            return ans;
        }

        int l,r,mid;
        l=0; r=len-1;
        while (l<=r)
        {
            mid=(l+r)/2;
            if (nums[mid]==target)
            {
                if (l+1==r || l==r) break;
                else
                if (nums[mid-1]==target) r=mid-1;
                else
                {
                    l=r=mid;
                    break;
                }
            }
            else
            if (nums[mid]>target)
                r=mid-1;
            else
                l=mid+1;
        }
        if (nums[l]!=target)
        {
            ans.push_back(-1);
            ans.push_back(-1);
            return ans;
        }

        ans.push_back(l);
        l=0; r=len-1;
        while (l<=r)
        {
            mid=(l+r+1)/2;
            if (nums[mid]==target)
            {
                if (l+1==r || l==r) break;
                else
                if (mid+1<len && nums[mid+1]==target) l=mid+1;
                else
                {
                    l=r=mid;
                    break;
                }
            }
            else
            if (nums[mid]>target)
                r=mid-1;
            else
                l=mid+1;
        }
        ans.push_back(r);
        return ans;
    }
};

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

返回将target按序插入数列中的所在位置

简单二分

class Solution
{
public:
    int searchInsert(vector<int>& nums, int target)
    {
        if (nums.size()==0) return 0;
        int l,r,mid;
        l=0;
        r=nums.size()-1;

        while (l<=r)
        {
            mid=(l+r)/2;
            if (nums[mid]==target) return mid;

            if (nums[mid]<target) l=mid+1;
            else r=mid-1;
        }
        return l;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-11-15 12:26:53

leetcode 题解代码整理 31-35题的相关文章

leetcode 题解代码整理 36-40题

Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. 判断数独当前状态是否合法 class Solut

leetcode 题解代码整理 1-5题

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please no

leetcode 题解代码整理 21-25题

Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 合并两个有序链表 /** * Definition for singly-linked list. * struct ListNode { * int val; * Li

leetcode 题解代码整理 6-10题

ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line

【题解整理】二分题

[题解整理]二分题 题目类型: 二分查找: 二分答案. 大致解题思路: 查找注意有序和返回值: 浮点数注意精度: 整数注意返回值,建议另外维护一个变量,用于储存可行解. 题目 分类 传送门 WA点 poj 2785 二分查找 题解 lightoj 1088 二分查找 题解 lightoj 1307 二分查找 题解 longlong poj 2456 整数二分答案 题解 poj 3104 整数二分答案 题解 poj 3258 整数二分答案 题解 poj 3273 整数二分答案 题解 lightoj

【LeetCode】树(共94题)

[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 - n 的所有形态的BST. 题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

leetcode题解:Binary Tree Postorder Traversal (二叉树的后序遍历)

题目: Given a binary tree, return the postorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? 说明: 1) 两种实现,递归与非递归 , 其中非递归有两种方法 2)复杂度分析:时

leetcode题解:Tree Level Order Traversal II (二叉树的层序遍历 2)

题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its bottom-up level order tr