Wednesday, April 13, 2022

Leet Code 41. First Missing Positive

https://leetcode.com/problems/first-missing-positive/ 

Example 1:

Input: nums = [3,4,-1,1]
Output: 2




jo bhi number inrange hai na, jese 5th index pr 2 mila toh 2 ko 2nd index wale number ke sath swap kr do, toh jo number present hain woh aopni sahi jgh pr pauch jaenge 

then, array ko traverse krnege toh, 0th index pr 1 hona chye, jh apr bhi aesa na ho, whi index wala number hi humara answer bnn jaega.






public class LeetCode_41_First_Missing_Positive {
// brute force: pehle sort kr do, then, check kro pehle no. 1 hona cheye then 2...
public static void main(String[] args) {
int[] arr = new int[]{3, 4, -1, 1};
System.out.print(firstMissingPositive(arr));
}

public static int firstMissingPositive(int[] nums) {
int i = 0, n = nums.length;

while (i < n) {
if (nums[i] > 0 && nums[i] < n + 1 && nums[nums[i] - 1] != nums[i]) {
swap(nums, i, nums[i] - 1);
} else {
i++;
}
}

i = 0;
while (i < n) {
if (nums[i] != i++ + 1)
return i;
}

return n + 1;
}

public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...