📌  相关文章
📜  给定数组中索引三元组 (i, j, k) 的计数,使得 i <j<k and a[j]<a[k]<a[i]

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

给定数组中索引三元组 (i, j, k) 的计数,使得 i

给定一个数组arr[] ,任务是计算三元组的数量,使得i < j

例子:

朴素方法:使用三个循环检查a[]中所有可能的三元组,并计算arr[]中三元组的数量,使得 i 

C++
// C++ code for the above approach
#include 
using namespace std;
 
int findTriplets(int a[], int n)
{
 
    // To count desired triplets
    int cnt = 0;
 
    // Three loops to find triplets
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            for (int k = j + 1; k < n; k++)
            {
 
                if (a[j] < a[k] && a[k] < a[i])
                    cnt++;
            }
        }
    }
 
    // Return the number of triplets found
    return cnt;
}
 
// Driver code
int main()
{
    int a[] = {2, 1, -3, -2, 5};
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << (findTriplets(a, n));
    return 0;
}
 
// This code is contributed by Potta Lokesh


Java
// Java Program for above approach
import java.io.*;
 
class GFG {
 
    public static int findTriplets(int[] a)
    {
 
        // To count desired triplets
        int cnt = 0;
 
        // Three loops to find triplets
        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                for (int k = j + 1; k < a.length; k++) {
 
                    if (a[j] < a[k] && a[k] < a[i])
                        cnt++;
                }
            }
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 2, 1, -3, -2, 5 };
 
        System.out.println(findTriplets(a));
    }
}


Python3
# Python Program for above approach
def findTriplets(a):
 
  # To count desired triplets
  cnt = 0;
 
  # Three loops to find triplets
  for i in range(len(a)):
    for j in range(i + 1, len(a)):
      for k in range(j + 1, len(a)):
        if (a[j] < a[k] and a[k] < a[i]):
          cnt += 1
 
  # Return the number of triplets found
  return cnt;
 
# Driver code
a = [2, 1, -3, -2, 5];
print(findTriplets(a));
 
# This code is contributed by Saurabh Jaiswal


C#
// C# Program for above approach
using System;
public class GFG {
 
  public static int findTriplets(int[] a)
  {
 
    // To count desired triplets
    int cnt = 0;
 
    // Three loops to find triplets
    for (int i = 0; i < a.Length; i++) {
      for (int j = i + 1; j < a.Length; j++) {
        for (int k = j + 1; k < a.Length; k++) {
 
          if (a[j] < a[k] && a[k] < a[i])
            cnt++;
        }
      }
    }
 
    // Return the number of triplets found
    return cnt;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int []a = { 2, 1, -3, -2, 5 };
 
    Console.WriteLine(findTriplets(a));
  }
}
 
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ program for above approach
 
#include 
using namespace std;
 
// Function to find desired triplets
int findTriplets(vector& a)
{
 
    // To store the number of triplets found
    int cnt = 0;
 
    stack st;
 
    // Keep track of second minimum element
    int secondMin = INT_MAX;
 
    for (int i = a.size() - 1; i >= 0; i--) {
 
        // If required triplet is found
        if (a[i] > secondMin)
            cnt++;
 
        while (!st.empty() && st.top() > a[i]) {
 
            secondMin = st.top();
            st.pop();
        }
        st.push(a[i]);
    }
   
    // Return the number of triplets found
    return cnt;
}
 
// Driver code
int main()
{
    vector a = { 2, 1, -3, -2, 5 };
 
    // Print the required result
    cout << findTriplets(a);
    return 0;
}
 
    // This code is contributed by rakeshsahni


Java
// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find desired triplets
    public static int findTriplets(int[] a)
    {
 
        // To store the number of triplets found
        int cnt = 0;
 
        Stack stack = new Stack<>();
 
        // Keep track of second minimum element
        int secondMin = Integer.MAX_VALUE;
 
        for (int i = a.length - 1; i >= 0; i--) {
 
            // If required triplet is found
            if (a[i] > secondMin)
                cnt++;
 
            while (!stack.isEmpty()
                   && stack.peek() > a[i]) {
 
                secondMin = stack.pop();
            }
            stack.push(a[i]);
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 2, 1, -3, -2, 5 };
 
        // Print the required result
        System.out.println(findTriplets(a));
    }
}


Python3
# Python 3 program for above approach
import sys
 
# Function to find desired triplets
def findTriplets(a):
 
    # To store the number of triplets found
    cnt = 0
    st = []
 
    # Keep track of second minimum element
    secondMin = sys.maxsize
    for i in range(len(a) - 1, -1, -1):
 
        # If required triplet is found
        if (a[i] > secondMin):
            cnt += 1
 
        while (not len(st) == 0 and st[-1] > a[i]):
 
            secondMin = st[-1]
            st.pop()
 
        st.append(a[i])
 
    # Return the number of triplets found
    return cnt
 
# Driver code
if __name__ == "__main__":
    a = [2, 1, -3, -2, 5]
 
    # Print the required result
    print(findTriplets(a))
 
    # This code is contributed by ukasp.


C#
// C# program for above approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to find desired triplets
    public static int findTriplets(int[] a)
    {
 
        // To store the number of triplets found
        int cnt = 0;
 
        Stack stack = new Stack();
 
        // Keep track of second minimum element
        int secondMin = int.MaxValue;
 
        for (int i = a.Length - 1; i >= 0; i--) {
 
            // If required triplet is found
            if (a[i] > secondMin)
                cnt++;
 
            while (stack.Count!=0
                   && stack.Peek() > a[i]) {
 
                secondMin = stack.Pop();
            }
            stack.Push(a[i]);
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []a = { 2, 1, -3, -2, 5 };
 
        // Print the required result
        Console.WriteLine(findTriplets(a));
    }
}
 
// This code is contributed by shikhasingrajput


Javascript


输出
2

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

有效方法:可以使用堆栈来优化上述解决方案。堆栈将跟踪右侧的下一个较小和第二个较小的元素。

请按照以下步骤解决给定的问题。

  • 创建一个堆栈和变量说secondMin = INT_MAX
  • 声明一个变量说cnt = 0来存储所需的三元组的数量。
  • 从数组a[]的末尾开始遍历。
    • 检查当前元素是否大于secondMin ,如果是,则表示找到所需的三元组,因为 堆栈正在跟踪下一个较小和第二个较小的元素,并且当前元素满足该类型。然后,设置cnt = cnt + 1
    • 如果不满足上述条件,则更新中的最小值,一直弹出直到不为空或当前元素不小于栈顶
    • 将当前元素压入堆栈
  • 最后返回cnt作为找到的三元组的数量。

下面是上述方法的实现:

C++

// C++ program for above approach
 
#include 
using namespace std;
 
// Function to find desired triplets
int findTriplets(vector& a)
{
 
    // To store the number of triplets found
    int cnt = 0;
 
    stack st;
 
    // Keep track of second minimum element
    int secondMin = INT_MAX;
 
    for (int i = a.size() - 1; i >= 0; i--) {
 
        // If required triplet is found
        if (a[i] > secondMin)
            cnt++;
 
        while (!st.empty() && st.top() > a[i]) {
 
            secondMin = st.top();
            st.pop();
        }
        st.push(a[i]);
    }
   
    // Return the number of triplets found
    return cnt;
}
 
// Driver code
int main()
{
    vector a = { 2, 1, -3, -2, 5 };
 
    // Print the required result
    cout << findTriplets(a);
    return 0;
}
 
    // This code is contributed by rakeshsahni

Java

// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find desired triplets
    public static int findTriplets(int[] a)
    {
 
        // To store the number of triplets found
        int cnt = 0;
 
        Stack stack = new Stack<>();
 
        // Keep track of second minimum element
        int secondMin = Integer.MAX_VALUE;
 
        for (int i = a.length - 1; i >= 0; i--) {
 
            // If required triplet is found
            if (a[i] > secondMin)
                cnt++;
 
            while (!stack.isEmpty()
                   && stack.peek() > a[i]) {
 
                secondMin = stack.pop();
            }
            stack.push(a[i]);
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 2, 1, -3, -2, 5 };
 
        // Print the required result
        System.out.println(findTriplets(a));
    }
}

Python3

# Python 3 program for above approach
import sys
 
# Function to find desired triplets
def findTriplets(a):
 
    # To store the number of triplets found
    cnt = 0
    st = []
 
    # Keep track of second minimum element
    secondMin = sys.maxsize
    for i in range(len(a) - 1, -1, -1):
 
        # If required triplet is found
        if (a[i] > secondMin):
            cnt += 1
 
        while (not len(st) == 0 and st[-1] > a[i]):
 
            secondMin = st[-1]
            st.pop()
 
        st.append(a[i])
 
    # Return the number of triplets found
    return cnt
 
# Driver code
if __name__ == "__main__":
    a = [2, 1, -3, -2, 5]
 
    # Print the required result
    print(findTriplets(a))
 
    # This code is contributed by ukasp.

C#

// C# program for above approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to find desired triplets
    public static int findTriplets(int[] a)
    {
 
        // To store the number of triplets found
        int cnt = 0;
 
        Stack stack = new Stack();
 
        // Keep track of second minimum element
        int secondMin = int.MaxValue;
 
        for (int i = a.Length - 1; i >= 0; i--) {
 
            // If required triplet is found
            if (a[i] > secondMin)
                cnt++;
 
            while (stack.Count!=0
                   && stack.Peek() > a[i]) {
 
                secondMin = stack.Pop();
            }
            stack.Push(a[i]);
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []a = { 2, 1, -3, -2, 5 };
 
        // Print the required result
        Console.WriteLine(findTriplets(a));
    }
}
 
// This code is contributed by shikhasingrajput

Javascript


输出
2

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