Leetcode

Check if an Array Is Consecutive

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  bool isConsecutive(vector<int>& nums) {
    const int n = nums.size();
    const int max = *max_element(begin(nums), end(nums));
    const int min = *min_element(begin(nums), end(nums));
    return max - min + 1 == n &&
           unordered_set<int>{begin(nums), end(nums)}.size() == n;
  }
};

JAVA

class Solution {
  public boolean isConsecutive(int[] nums) {
    final int n = nums.length;
    final int max = Arrays.stream(nums).max().getAsInt();
    final int min = Arrays.stream(nums).min().getAsInt();
    return max - min + 1 == n &&
        Arrays.stream(nums).boxed().collect(Collectors.toSet()).size() == n;
  }
}

Python

class Solution:
  def isConsecutive(self, nums: List[int]) -> bool:
    return max(nums) - min(nums) + 1 == len(set(nums)) == len(nums)