Advertisement
maycod23

Rotated_Sorted_Array

Apr 28th, 2023
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. //rotated sorted array questions:
  2.  
  3. //Q-1: https://leetcode.com/problems/search-in-rotated-sorted-array/
  4.  
  5. class Solution {
  6. public:
  7. int search(vector<int>& a, int key)
  8. {
  9. int n=a.size();
  10. int l=0,r=n-1;
  11. while(l<=r)
  12. {
  13. int mid=l+(r-l)/2;
  14. if(a[mid]==key) return mid;
  15. if(a[mid]>=a[l])//left sorted
  16. {
  17. if(key<=a[mid]&&key>=a[l])
  18. {
  19. r=mid-1; continue;
  20. }
  21. else
  22. {
  23. l=mid+1; continue;
  24. }
  25. }
  26. else//right part sorted
  27. {
  28. if(key<=a[r]&&key>=a[mid])
  29. {
  30. l=mid+1; continue;
  31. }
  32. else
  33. {
  34. r=mid-1; continue;
  35. }
  36. }
  37. }
  38. return -1;
  39. }
  40. };
  41.  
  42.  
  43.  
  44.  
  45.  
  46. //Q-2: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/
  47.  
  48.  
  49. class Solution {
  50. public:
  51. bool search(vector<int>& a, int key)
  52. {
  53. int n=a.size();
  54. int l=0,r=n-1;
  55. while(l<=r)
  56. {
  57. int mid=l+(r-l)/2;
  58. if(key==a[mid]) return true;
  59. if(a[l]<a[mid])//left striclty sorted
  60. {
  61. if(key<a[mid]&&key>=a[l])
  62. {
  63. r=mid-1; continue;
  64. }
  65. else
  66. {
  67. l=mid+1; continue;
  68. }
  69. }
  70. else if(a[l]==a[mid])
  71. {
  72. l++; continue;
  73. }
  74. else//right sorted
  75. {
  76. if(key<=a[r]&&key>a[mid])
  77. {
  78. l=mid+1; continue;
  79. }
  80. else
  81. {
  82. r=mid-1; continue;
  83. }
  84. }
  85. }
  86. return false;
  87. }
  88. };
  89.  
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement