Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. /**
  2. * So basically, we want to first turn all values < 0 to null.
  3. * Then, using 1-indexing (First value of array is index 1 instead of 0), we change the number to a negative. The reason being is
  4. * that we want to hit either the first null or first positive, which indicates that that is the first number missing. A positive
  5. * number in the array will always change the value of the index it references to a negative, so the first value hit, which is the
  6. * first number missing, will always be either null or a positive value.
  7. * When changing the values to negatives, if the value is positive, we need to replace whatever value is there with a negative version
  8. * of itself. This is because we may pass over that number, and will need the original value, but also need to show that it should
  9. * be skipped in the final pass.
  10. * Lastly, the last step is to find either a number that is positive or null. A base case exists where if the array were empty, the
  11. * array were all null, or the array were all negative, it would always be 1.
  12. * */
  13. var firstMissingPositive = function(nums) {
  14. for (let i = 0; i < nums.length; i++) {
  15. if (nums[i] <= 0) {
  16. nums[i] = null;
  17. }
  18. }
  19.  
  20. console.log("Nums after first pass: ", nums);
  21.  
  22. for (let i = 0; i < nums.length; i++) {
  23. console.log("Current iteration: ", i, "\tNum: ", nums[i]);
  24. if (nums[i] !== null) {
  25. console.log("nums[Math.abs(", nums[i], ") - 1]): ", nums[Math.abs(nums[i]) - 1])
  26. if (nums[Math.abs(nums[i]) - 1] > 0) {
  27. console.log("Changing ", nums[Math.abs(nums[i]) - 1], " to ", -nums[Math.abs(nums[i]) - 1])
  28. nums[Math.abs(nums[i]) - 1] = -nums[Math.abs(nums[i]) - 1];
  29. } else if (nums[Math.abs(nums[i]) - 1] === null) {
  30. console.log("Value is null, changing to negative length: ", -(nums.length));
  31. nums[Math.abs(nums[i]) - 1] = -(nums.length);
  32. } else {
  33. console.log("Will not do anything. Num either undefined or negative.")
  34. }
  35. } else {
  36. console.log("Pass");
  37. }
  38. console.log("Nums at end of iteration ", i, ": ", nums);
  39. }
  40.  
  41. console.log("Nums after second pass: ", nums);
  42.  
  43. for (let i = 0; i < nums.length; i++) {
  44. if (nums[i] > 0 || nums[i] === null) {
  45. return i + 1;
  46. }
  47. }
  48.  
  49. return nums.length + 1;
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement