查找第K最小的元素在未排序的载体(迭代)

编程入门 行业动态 更新时间:2024-10-26 04:25:43
本文介绍了查找第K最小的元素在未排序的载体(迭代)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图做一个code,它返回一个矢量的第k个最小元素。 例如: 比方说你有一个载体兰特其中包含的元素{0,3,2,5} 而用户输入2作为K赋值 该函数应该然后返回元件2从载体,因为它是第2次(第k)最小的元素在载体

I'm trying to make a code that returns the kth smallest element in a vector. For example: Lets say you have a vector rand which contains elements {0, 3, 2, 5} And the user inputs 2 as a value for K. The function should then return element 2 from the vector since it is the 2nd (kth) smallest element in the vector.

到目前为止,这是我的code:

so far this is my code:

int iterative_kth_element(vector<int>& vec, size_t k) { int index = 0; int min = vec[0]; for(int i = k;i<vec.size();i--) { for (int j = 1; j < vec.size();j++) { if ( min > vec[j] ) { min = vec[j]; index = i; } vec.erase(vec.begin() + index); if (i == 1) { return min; } } } }

它保持返回一些巨大的数字,是不是即使在载体中。

it keeps returning some huge number that is not even in the vector.

推荐答案

从这里开始:的http:// EN .wikipedia /维基/ Selection_algorithm

int iterative_kth_element(vector<int>& vec, size_t k) { int minIndex, minValue; for (int i = 0; i < k; i++) { minIndex = i; minValue = vec[i]; for (int j = i+1; j < n; j++) { if (vec[j] < minValue) { minIndex = j; minValue = vec[j]; } } int tmp = vec[i]; vec[i] = vec[minIndex]; vec[minIndex] = tmp; } return vec[k]; }

更多推荐

查找第K最小的元素在未排序的载体(迭代)

本文发布于:2023-11-29 17:38:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:载体   最小   元素   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!