You are given all numbers between except one. Your task is to find the missing number.
Example:
Input: n = 5, arr = [2,3,1,5]
Output: 4
Approach
Java
import java.util.Arrays;public class MissingNumber {public static void main(String[] args) {int n = 5;int arr[] = { 2, 3, 1, 5 };System.out.println(missingNumber(n, arr));}static int missingNumber(int n, int arr[]) {Arrays.sort(arr);int ans = 1;for (int i = 0; i < n; i++) {if (arr[i] != i + 1) {ans = i + 1;break;}}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int missingNumber(int n, int arr[]){sort(arr, arr + n - 1);int ans = 1;for (int i = 0; i < n; i++){if (arr[i] != i + 1){ans = i + 1;break;}}return ans;}int main(){int n = 5;int arr[n - 1] = {2, 3, 1, 5};cout << missingNumber(n, arr);return 0;}
No comments:
Post a Comment