LeetCode215. Kth Largest Element in an Array

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_41042404/article/details/88423158

Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

1. std::sort(),reverse().O(nlogn)

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        sort(nums.begin(),nums.end());
        reverse(nums.begin(),nums.end());
        return nums[k-1]; 
    }
};

2.Partition.O(n)

#include <vector>
using namespace std;

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) 
    {
        if(nums.empty()||k>nums.size())
        return 0;

        k=nums.size()-k;//从小到大排列后的k
        QuickSort_Recur(nums,0,nums.size()-1);
 
        return nums[k];
    }
     void QuickSort_Recur(vector<int>& nums, int low, int high)
    { 
        if(low<high)
        {
            int index = Partition(nums,low,high);//找到一个基准,并将所有小于基准的数放在基准左边。
            QuickSort_Recur(nums,low,index-1);
            QuickSort_Recur(nums,index+1,high);
        }
    }

    int Partition(vector<int>& nums,int start,int end)
    {
        if(start<0||end>=nums.size())
          return 0;

        int pivot = random(start,end);
        swap(&nums[pivot],&nums[end]);//把基准移到尾部
        
        int left = start -1;//最左边原地划分一个子集
        for(int i =start;i<end;i++)
        {
            if(nums[i]<nums[end])//如果小于基准就放入子集中
            {
                left++;
                if(left!=i)
                    swap(&nums[i],&nums[left]);
            }
        }

        left++;
        swap(&nums[left],&nums[end]);//将最尾部的基准放在左子集的下一个位置

        return left;//返回基准
     }
    int random(int min,int max)
    {
        int random =rand()%(max-min+1) +min;
        return random;
    }
    void swap(int *in1,int* in2){
        int temp=*in1;
        *in1=*in2;
        *in2=temp;
    }
};

3.heap. STL的Priority queue

max-heap:将N个元素塞入一个最大堆,将堆顶元素删除k-1次。堆顶就是要找的第K大的元素。
min-heap:将K个最大元素塞入一个最小堆。堆顶就是要找的第K大的元素。
在STL中。priority_queuemultiset可以实现最大堆/最小堆。

using priority_queue

min-heap

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int>> pq;
        for (int num : nums) {
            pq.push(num);
            if (pq.size() > k) {
                pq.pop();
            }
        }
        return pq.top();
    }
};

max-heap

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int> pq(nums.begin(), nums.end());
        for (int i = 0; i < k - 1; i++) {
            pq.pop();
        }
        return pq.top();
    }
};

using multiset(rbt)

min-heap

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        multiset<int> mset;
        for (int num : nums) {
            mset.insert(num);
            if (mset.size() > k) {
                mset.erase(mset.begin());
            }
        }
        return *mset.begin();
    }
};

max-heap

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        multiset<int, greater<int>> mset(nums.begin(), nums.end());
        for (int i = 0; i < k - 1; i++) {
            mset.erase(mset.begin());
        }
        return *mset.begin();
    }
};

4.STL的nth_element和partial_sort

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), greater<int>());
        return nums[k - 1];
    }
};
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        partial_sort(nums.begin(), nums.begin() + k, nums.end(), greater<int>());
        return nums[k - 1];
    }
};

请注意两个内置函数的第二个参数中的1之差。

展开阅读全文

java.lang.IllegalArgumentException: array element type mismatch求解决办法

04-18

java.lang.IllegalArgumentException: array element type mismatchrnat java.lang.reflect.Array.set(Native Method)rnat org.apache.commons.beanutils.ConvertUtils.convert(ConvertUtils.java:415)rnat org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:983)rnat org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:808)rnat org.apache.struts.util.RequestUtils.populate(RequestUtils.java:467)rnat org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:818)rnat org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:194)rnat org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)rnat org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)rnat javax.servlet.http.HttpServlet.service(HttpServlet.java:710)rnat javax.servlet.http.HttpServlet.service(HttpServlet.java:803)rnat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rnat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rnat com.iwtxokhtd.news.web.filter.EncodingFilter.doFilter(EncodingFilter.java:27)rnat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rnat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rnat org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:112)rnat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)rnat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rnat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rnat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rnat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)rnat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rnat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rnat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rnat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)rnat org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)rnat org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)rnat org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)rnat java.lang.Thread.run(Thread.java:595)rn------------------------rn代码:rnaddprivilegegroup.jsp:rn---rnrnrn rn 添加权限组rn rn rn 权限组名称rn rn *rn rn rn 选择权限rn rnrn$privilege.name  rn rn rn---------------------rnPrivilegeGroupForm.java:rn---rnprivate String name;rnprivate SystemPrivilegePK[] privileges;rnprivate Integer groupid;rnrnpublic Integer getGroupid() rnreturn groupid;rnrnrnpublic void setGroupid(Integer groupid) rnthis.groupid = groupid;rnrnrnpublic String getName() rnreturn name;rnrnrnpublic void setName(String name) rnthis.name = name;rnrnrnpublic SystemPrivilegePK[] getPrivileges() rnreturn privileges;rnrnrnpublic void setPrivileges(SystemPrivilegePK[] privileges) rnthis.privileges = privileges;rnrn---------------rnSystemPrivielgePK.java:rn---rn@Embeddablernpublic class SystemPrivilegePK implements Serializable rnrn/**rn * rn */rnprivate static final long serialVersionUID = 2984271915721771745L;rn//模块rnprivate String model;rn//权限值rnprivate String privilegeValue;rnrnpublic SystemPrivilegePK() rnrnpublic SystemPrivilegePK(String model, String privilegeValue) rnthis.model = model;rnthis.privilegeValue = privilegeValue;rnrn@Column(length=30,name="model")rnpublic String getModel() rnreturn model;rnrnpublic void setModel(String model) rnthis.model = model;rnrn@Column(length=20,name="privilegeValue")rnpublic String getPrivilegeValue() rnreturn privilegeValue;rnrnpublic void setPrivilegeValue(String privilegeValue) rnthis.privilegeValue = privilegeValue;rnrn---------------------rn也就是说:jsp页面中的是个数组,且form中定义了一个SystemPrivilegePK[]privileges数组,但这数组不是简单类型的,因此添加时出现了上面的异常,现在是SystemPrivilegePK[]privileges不能改变的前提下该如何解决上述异常并能正确添加数据? 论坛

The Kth BST

03-23

Definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.nnDefinition: A binary search tree(BST) is a binary tree. It may be empty. If it is not empty, it satisfies the following properties:nnEvery elements has a key, and no two elements have the same key, that is, the keys are unique.nThe keys in a nonempty left subtree must be smaller than the key in the root of the subtree.nThe keys in a nonempty right subtree must be larger than the key in the root of the subtree.nThe left and right subtrees are also binary search trees.nIn this problem, we just care about the Preorder Traversal of a BST. Here is the pseudocode for Preorder Traversal:nnvoid preorder(tree_pointer ptr)n/* preorder tree traversal */nn if (ptr) n printf("%d", ptr->data);n preorder(ptr->left_child);n preorder(ptr->right_child);n nnNow, you are given n, the number of nodes in a BST, and the nodes of the BST are consist of the first n lowcase letters. Of course, more than one BST can be constructed except when n is 1. You task is to sort there BST's according to their preorder representations, and gives out the Kth BST.nnFor example, when n is 2, there are two BST's can be constructed, as following:nna bn \ /n b anTheir preorder representations are: ab and ba, so the first one is ab, and the second one is ba.nnInputnnThere are multiple test cases in this problem. The input is terminated by EOF.nnFor each test case, there are two inputs: n and K, representing the number of nodes in the BST, and the index of the BST you need to output.nnNote:nnn is between 1 and 19nK is between 1 and the number of ways to construct the BSTnOutputnnFor each input, you should first output the Kth preorder representation of the BST. Next, for each node (in the order a, b, c, ...), output it first, then output the left sub node (output * if not exist) and the right sub node (output * if not exist), seperated by a single blank space. K will not be greater than the number of representations of BST given n nodes. Output a blank line between two test cases.nnSample Inputnn2 2n4 9nSample Outputnnbana * *nb a *nncbadna * *nb a *nc b dnd * *n 问答

没有更多推荐了,返回首页