📌  相关文章
📜  以给定数组的排序形式查找给定元素的所有索引

📅  最后修改于: 2022-05-13 01:56:07.049000             🧑  作者: Mango

以给定数组的排序形式查找给定元素的所有索引

给定一个大小为N的整数数组arr[]和一个目标值val 。您的任务是在对数组进行升序排序后找到数组中 val 的索引

注意:索引必须按升序排列。

例子:

Naive Approach:这种方法的概念是基于排序的。数组按升序排序。然后遍历排序后的数组。如果任何值与目标匹配,则在遍历数组时,该索引将添加到答案列表中。迭代完成后返回答案列表。
时间复杂度: O(N*logN)
辅助空间: O(1)

高效方法:这种方法基于对排序数组的观察。在一个按升序排序的数组中, val 之前的所有元素都小于val。因此,要获取排序数组中val的索引,我们可以简单地计算小于val的元素,而不是执行排序操作。如果计数为 x ,则val将从第 x 个索引开始(因为基于 0 的索引)。请按照以下步骤操作:

  • 遍历数组。使用变量来存储小于 val ( smallCount ) 的元素的计数以及与 val ( sameCount ) 具有相同值的元素。
  • 如果元素的值小于 val,则将 smallCount加一。
  • 如果 value与 val 相同,则将 sameCount加一。
  • 遍历完成后,索引将从 smallCount 开始,到 (smallCount+sameCount-1) 结束

下面是上述方法的实现:

C++

// C++ implementation of the above approach
 
#include 
using namespace std;
 
// Function to find indices
// of val in array after sorting
vector targetIndices(vector& nums, int val)
{
    int count_less = 0;
    int count_target = 0;
 
    // Loop to count smaller elements and val
    for (auto& it : nums) {
        if (it == val)
            count_target++;
        if (it < val)
            count_less++;
    }
 
    // List to store indices
    vector ans;
    while (count_target--) {
        ans.push_back(count_less++);
    }
    return ans;
}
 
// Driver code
int main()
{
    vector nums{ 1, 2, 5, 2, 3 };
    int val = 2;
    vector ans = targetIndices(nums, val);
 
    // Loop to print indices
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}

Java

// Java implementation of the above approach
import java.util.*;
public class GFG {
 
    // Function to find indices
    // of val in array after sorting
    static List targetIndices(int[] nums, int val)
    {
        int count_less = 0;
        int count_target = 0;
 
        // Loop to count smaller elements and val
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val)
                count_target++;
            if (nums[i] < val)
                count_less++;
        }
 
        // List to store indices
        List ans = new ArrayList();
        while (count_target > 0) {
            ans.add(count_less++);
            count_target--;
        }
        return ans;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] nums = { 1, 2, 5, 2, 3 };
        int val = 2;
        List ans = targetIndices(nums, val);
 
        // Loop to print indices
        for (int i = 0; i < ans.size(); i++) {
            zz System.out.print(ans.get(i) + " ");
        }
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Python3

# python implementation of the above approach
 
# Function to find indices
# of val in array after sorting
def targetIndices(nums, val):
 
    count_less = 0
    count_target = 0
 
    # Loop to count smaller elements and val
    for it in nums:
        if (it == val):
            count_target += 1
        if (it < val):
            count_less += 1
 
        # List to store indices
    ans = []
    while (count_target):
        count_target -= 1
        ans.append(count_less)
        count_less += 1
 
    return ans
 
# Driver code
if __name__ == "__main__":
 
    nums = [1, 2, 5, 2, 3]
    val = 2
    ans = targetIndices(nums, val)
 
    # Loop to print indices
    for i in range(0, len(ans)):
        print(ans[i], end=" ")
 
    # This code is contributed by rakeshsahni

C#

// C# implementation of the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG {
 
    // Function to find indices
    // of val in array after sorting
    static ArrayList targetIndices(int[] nums, int val)
    {
        int count_less = 0;
        int count_target = 0;
 
        // Loop to count smaller elements and val
        for (int i = 0; i < nums.Length; i++) {
            if (nums[i] == val)
                count_target++;
            if (nums[i] < val)
                count_less++;
        }
 
        // List to store indices
        ArrayList ans = new ArrayList();
        while (count_target > 0) {
            ans.Add(count_less++);
            count_target--;
        }
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        int[] nums = { 1, 2, 5, 2, 3 };
        int val = 2;
        ArrayList ans = targetIndices(nums, val);
 
        // Loop to print indices
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i] + " ");
        }
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript


输出
// C++ implementation of the above approach
 
#include 
using namespace std;
 
// Function to find indices
// of val in array after sorting
vector targetIndices(vector& nums,
                          int val)
{
    int count_less = 0;
    int count_target = 0;
 
    // Loop to count smaller elements and val
    for (auto& it : nums) {
        if (it == val)
            count_target++;
        if (it < val)
            count_less++;
    }
 
    // List to store indices
    vector ans;
    while (count_target--) {
        ans.push_back(count_less++);
    }
    return ans;
}
 
// Driver code
int main()
{
    vector nums{ 1, 2, 5, 2, 3 };
    int val = 2;
    vector ans = targetIndices(nums, val);
 
    // Loop to print indices
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}

时间复杂度: O(N)
辅助空间: O(1)