Skip to content

Instantly share code, notes, and snippets.

@airekans
Created December 12, 2012 15:45
Show Gist options
  • Save airekans/4268836 to your computer and use it in GitHub Desktop.
Save airekans/4268836 to your computer and use it in GitHub Desktop.
Least positive number in an array of integer numbers.
def least_positive(nums):
length = len(nums)
is_valid = lambda e: 0 < e <= length
def swap(i, j):
nums[i], nums[j] = nums[j], nums[i]
i = 0
while i < length:
e = nums[i]
if is_valid(e) and nums[e - 1] != e:
swap(i, e - 1)
else:
i += 1
print nums
for i, e in enumerate(nums):
if not is_valid(e) or i != e - 1:
return i + 1
return length + 1
if __name__ == '__main__':
print least_positive([0, 1, 3])
print least_positive([-1, 2, 1, -3, 2, 4])
print least_positive([0, 0, 3, 3, 3, 2, 1, 1])
print least_positive([0, 0])
print least_positive([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment