Given an array of integers nums containing
n + 1
integers where each integer is in the range [1, n]
inclusive.There is only one repeated number in
nums
, return this repeated number.Example 1:
Input: nums ={1,3,4,2,2} Output: 2
Approach
Java
import java.util.Arrays;public class FindDuplicateNumber {public static void main(String[] args) {int[] nums = { 1, 3, 4, 2, 2 };System.out.println(findDuplicate(nums));}static int findDuplicate(int[] nums) {Arrays.sort(nums);int res = 0;for (int i = 0; i < nums.length - 1; i++)if (nums[i] == nums[i + 1]) {res = nums[i];break;}return res;}}
C++
#include <bits/stdc++.h>using namespace std;int findDuplicate(vector<int>& nums){sort(nums.begin(),nums.end());int res=0;for(int i=0;i<nums.size()-1;i++)if(nums[i]==nums[i+1]){res=nums[i];break;}return res;}int main(){vector<int> nums ={1,3,4,2,2};cout<<findDuplicate(nums);return 0;}
No comments:
Post a Comment