Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. C++:
  2. class Solution {
  3. public:
  4. int firstMissingPositive(int A[], int n) {
  5. // Start typing your C/C++ solution below
  6. // DO NOT write int main() function
  7. for(int i=0;i<n;i++){
  8. if(A[i]>0&&A[i]<=n){
  9. if(A[i]-1!=i&&A[A[i]-1]!=A[i]){
  10. int temp=A[A[i]-1];
  11. A[A[i]-1]=A[i];
  12. A[i]=temp;
  13. i--;
  14. }
  15. }
  16. }
  17. for(int i=0;i<n;i++)
  18. if(A[i]!=i+1)
  19. return i+1;
  20. return n+1;
  21. }
  22. };
  23. Java:
  24. public class Solution {
  25. public int firstMissingPositive(int[] A) {
  26. // Start typing your Java solution below
  27. // DO NOT write main() function
  28. int n=A.length;
  29. for(int i=0;i<n;i++){
  30. if(A[i]>0&&A[i]<=n){
  31. if(A[i]-1!=i&&A[A[i]-1]!=A[i]){
  32. int temp=A[A[i]-1];
  33. A[A[i]-1]=A[i];
  34. A[i]=temp;
  35. i--;
  36. }
  37. }
  38. }
  39. for(int i=0;i<n;i++)
  40. if(A[i]!=i+1)
  41. return i+1;
  42. return n+1;
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement