如何查找vector <vector <int>&gt;的所有索引至少第一个索引

时间:2016-12-25 09:58:09

标签: c++ c++11

我有一个未分类的二维数据向量,包含重复的元素。

如何找到具有值的最小值和所有索引?

例如,给定数据vector<vector<int>> mySol = {{3,1},{1,2},{4,5},{1,3},{1,2}},我想找到{1,2}{1,3}{1,2},它们给出最小值1(基于第一个元素)和索引2,3和2。

如何改进以下代码段?对于大数据,由于sort

,以下代码似乎很慢
vector<vector<int>> mySol = {{3,1},{1,2},{4,5},{1,3},{1,2}};
sort(mySol.begin(), mySol.end());

//print out shortest distance
cout << mySol[0][0] << endl;

//print out the number of shortest paths
int nShortest = 0;
for (int i = 0; i < mySol.size(); i++) {
    if (mySol[0][0] == mySol[i][0])
        nShortest += 1;
}
cout << nShortest << "  ";

//print out y-coordinates of the shortest paths in increasing order
for (int i = 0; i < nShortest; i++) {
    cout << mySol[i][1] << " ";
}

2 个答案:

答案 0 :(得分:1)

您可以在线性时间内完成工作:

  • 首先找到最低要求
  • 然后迭代最小值。

类似的东西:

function solution(A) {
  // This array contains maximal value at any index.
  const maxTill = [A[0]];

  // It's a dynamic programming so we will choose maximal value at each
  // Index untill we reach last index (goal)
  for (let i = 1; i < A.length; i++) {
    // Step 1 . max value of each index will be atleast equal to or greater than
    // max value of last index.
    maxTill[i] = maxTill[i - 1];
    // For each index we are finxing the max of last 6 array value
    // And storing it into Max value.
    for (let dice = 1; dice <= 6; dice++) {
      // If array index is itself less than backtrack index
      // break as you dont have 6 boxes in your left
      if (dice > i) {
        break;
      } else {
        // The most important line .
        // Basically checking the max of last 6 box using a loop.
        maxTill[i] = Math.max(
          maxTill[i - dice],
          maxTill[i]
        );
      }
    }
    // Untill this point maxStill contains the maximal value
    // to reach to that index.
    // To end the game we need to touch that index as well , so
    // add the vale of the index as well.
    maxTill[i] += A[i];
  }
  return maxTill[A.length - 1];
}

console.log(solution([-1, -2, -3, -4, -3, -8, -5, -2, -3, -4, -5, -6, -1]));

答案 1 :(得分:0)

谢谢Jarod!根据Jarod的想法,我修改了代码如下。使用简单的min并避免使用find_if。这似乎更快,避免排序和找到最小。

vector<vector<int>> mySol = {{3,1},{1,2},{4,5},{1,3},{1,2}};
auto minIt = std::min(mySol.begin(), mySol.end());
cout << (*minIt)[0] << endl;

int nShortest = 0;
for (auto it = mySol.begin(); it != mySol.end(); ++it) {
    if ((*it)[0] == (*minIt)[0]) ++nShortest;
}
cout << nShortest << " ";

for (auto it = mySol.begin(); it != mySol.end(); ++it) {
    if ((*it)[0] == (*minIt)[0]) {
        cout << (*it)[1] << " ";
    }
}