You are given an array
Notice that
Return
nums
of non-negative integers. nums
is considered special if there exists a number x
such that there are exactly x
numbers in nums
that is greater than or equal to x
.Notice that
x
does not have to be an element in nums
.Return
x
if the array is special, otherwise, return -1
. It can be proven that if nums
is special, the value for x
is unique.Example 1:
Input: nums = [3,5]
Output: 2
Approach
Java
public class SpecialArrayWithXElem {public static void main(String[] args) {int[] nums = { 3, 5 };System.out.println(specialArray(nums));}static int specialArray(int[] nums) {mergeSort(nums, new int[nums.length], 0, nums.length-1);int res = 0;for (int i = 1; i <= nums.length; i++) {if (nums[i - 1] >= i)res = i;else if (nums[i - 1] == res)return -1;}return res;}// method for merge sortstatic void mergeSort(int arr[], int aux[], int low, int high) {// base caseif (high <= low)return;int mid = low + (high - low) / 2;// left subarraymergeSort(arr, aux, low, mid);// right subarraymergeSort(arr, aux, mid + 1, high);// merge two sortd arraymergeTwoSortedArray(arr, aux, low, mid, high);}static void mergeTwoSortedArray(int arr[], int aux[], int low,int mid, int high) {int k = low, i = low, j = mid + 1;while (i <= mid && j <= high) {// if right subarray value is greater// the insert the left subarray into// the resultif (arr[i] > arr[j]) {aux[k++] = arr[i];i++;}// otherwise insert the right subarray value// into the resultelse {aux[k++] = arr[j];j++;}}// if left subarray is remaining and right subaray is// overwhile (i <= mid)aux[k++] = arr[i++];// if right subarray is remaining and left subarray is// overwhile (j <= high)aux[k++] = arr[j++];// store result back to original arrayfor (int l = low; l <= high; l++)arr[l] = aux[l];}}
C++
#include <bits/stdc++.h>using namespace std;int specialArray(vector<int> &nums){sort(nums.begin(), nums.end(), greater<int>());int res = 0;for (int i = 1; i <= nums.size(); i++){if (nums[i - 1] >= i)res = i;else if (nums[i - 1] == res)return -1;}return res;}int main(){vector<int> nums = {3, 5};cout << specialArray(nums);return 0;}
No comments:
Post a Comment