In this Leetcode Missing Number problem solution, we have given an array num containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Problem solution in Python.
class Solution(object): def missingNumber(self, nums): L = len(nums) final = (1+L)*L/2 for i in nums: final -= i return final
Problem solution in Java.
public int missingNumber(int[] nums) { int sum = nums.length * (nums.length + 1) / 2; int series = 0; for (int num : nums) series += num; return sum - series; }
Problem solution in C++.
class Solution { public: int missingNumber(vector<int>& nums) { int n=nums.size(); set<int> s; for(int i=0;i<n;i++) { s.insert(nums[i]); } for(int i=0;i<=n;i++) { if(s.find(i)==s.end()) return i; } return -1; } };
Problem solution in C.
int missingNumber(int* nums, int numsSize) { int *result = calloc(numsSize, sizeof(int)); for(int i = 0; i < numsSize; i++){ result[nums[i]] = -1; } for(int i = 0; i < numsSize; i++){ if(result[i] >= 0) return i; } return numsSize; }
0 Comments