You are given an array of n integers, and your task is to find three values (at distinct positions) whose sum is x.
Example:
Input: n = 4, m = 8, arr = {2, 7, 5, 1}
Output: 4 1 3
Approach
Java
import java.util.Arrays;import java.util.Comparator;public class SumofThreeValues {public static void main(String[] args) {int n = 4, m = 8;int[] arr = { 2, 7, 5, 1 };sumOfThreeValues(n, m, arr);}static void sumOfThreeValues(int n, int m, int[] arr) {int[][] a = new int[n + 1][2];for (int i = 0; i < n; i++) {int x = arr[i];a[i][0] = x;a[i][1] = i + 1;}Arrays.sort(a, Comparator.comparingDouble(o -> o[0]));for (int u = 0; u < n; u++) {for (int i = u + 1, j = n - 1; i < j;) {if (a[u][0] + a[i][0] + a[j][0] == m) {System.out.println(a[u][1] + " " +a[i][1] + " " + a[j][1]);return;} else if (a[u][0] + a[i][0] + a[j][0] < m) {i++;} else {j--;}}}System.out.println("IMPOSSIBLE");}}
C++
#include <bits/stdc++.h>using namespace std;void sumOfThreeValues(int n, int m, vector<int> &arr){vector<array<int, 2>> a(n);for (int i = 0; i < n; i++){int x = arr[i];a[i] = {x, i + 1};}sort(a.begin(), a.end());for (int u = 0; u < n; u++){for (int i = u + 1, j = n - 1; i < j;){if (a[u][0] + a[i][0] + a[j][0] == m){cout << a[u][1] << " " << a[i][1] << " "<< a[j][1] << "\n";return;}else if (a[u][0] + a[i][0] + a[j][0] < m){i++;}else{j--;}}}cout << "IMPOSSIBLE\n";}int main(){int n = 4, m = 8;vector<int> arr = {2, 7, 5, 1};sumOfThreeValues(n, m, arr);return 0;}
No comments:
Post a Comment