Find Target Indices After Sorting Array in java

Find Target Indices After Sorting Array in java

You are given a 0-indexed integer array nums and a target element target.

A target index is an index i such that nums[i] == target.

print a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The printed list must be sorted in increasing order.

Input:

The first line of the input contains the number 𝑛(length of array) and the target t The next n integers denotes the elements of the array.

Output:

Print the indices where the target occured in sorted array Print -1 if no element is found that is equal to target

Constraints:

1 <= nums.length <= 100
1 <= nums[i] <= 100
Sample Input 1

5 2 1 2 5 2 3

Sample Output 1

1 2

Explanation

After sorting, nums is [1,2,2,3,5]. The indices where nums[i] == 2 are 1 and 2.

Sample Input 2
5 4
1 2 5 2 3
Sample Output 2
-1
Explanation

There are no elements in nums with value 4.

Solution of Find Target Indices After Sorting Array in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int t = sc.nextInt();
      
      int arr[] = new int[n];

      for(int i=0;i<n;i++)
        {
          arr[i]=sc.nextInt();
        }

      insertionSort(arr,n);
      int temp[] = new int[n];
      int count=0;
      for(int i=0;i<n;i++)
        {
          if(arr[i]==t)
          {
            temp[count]=i;
            count++;
          }
        }

      if(count>0)
      {
        for(int i=0;i<count;i++)
          {
            System.out.print(temp[i]+" ");
          }
      }
      else{
        System.out.println("-1");
      }
      
	}

  public static void insertionSort(int arr[], int n)
  {
     for(int i=1;i<n;i++)
       {
         for(int j=i-1;j>=0;j--)
           {
             if(arr[j]>arr[j+1])
             {
               int temp=arr[j];
               arr[j]=arr[j+1];
               arr[j+1]=temp;
             }
             else{
               break;
             }
           }
       }
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *