Given an array
nums
containing n
distinct numbers in the range [0, n]
, return the only number in the range that is missing from the array.Example:
Input: arr[]={3,0,1}
Output: 2
Approach
Java
public class MissingNumber {public static void main(String[] args) {int nums[] = { 3, 0, 1 };int missing = missingNumber(nums);System.out.println(missing);}// find the missing number in the array// all number are from 0 to n-1private static int missingNumber(int[] nums) {int n = nums.length;int res = 0;for (int i = 1; i <= n; i++)res = res ^ i;for (int i = 0; i < n; i++)res ^= nums[i];return res;}}
C++
#include <bits/stdc++.h>using namespace std;//find the missing number in the array//all number are from 0 to n-1int missingNumber(vector<int>& nums){int n=nums.size();int res=0;for(int i=1;i<=n;i++)res=res^i;for(int i=0;i<n;i++)res^=nums[i];return res;}int main(){vector<int> nums={3,0,1};int missing=missingNumber(nums);cout<<missing<<"\n";return 0;}
No comments:
Post a Comment