fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. }
  14. }
  15.  
  16. class Solution {
  17. public int search(int[] nums, int target) {
  18. int low = 0;
  19. int high = nums.length - 1;
  20.  
  21. if(nums.length == 2){
  22. if(nums[0] == target)
  23. return 0;
  24. if(nums[1] == target)
  25. return 1;
  26. return -1;
  27. }
  28. while(low<=high){
  29. int mid = (low+high)/2;
  30. if(nums[mid] == target){
  31. return mid;
  32. }
  33. else if(nums[mid] >= nums[low]){
  34. //it means thet the whole area of low till mid is sorted
  35. if(nums[mid]>target && nums[low] <= target){
  36. //that is target lies between
  37. high = mid - 1;
  38. }else{
  39. low = mid +1;
  40. }
  41.  
  42. }else{
  43. //it means that we are in the second half of the array that is unrotated part
  44. //like 7 8 9 10 1 2 3 4 5 6 and we are at 2
  45. if(nums[high]>=target && nums[mid]<target){
  46. //answer lies in this interval
  47. low = mid + 1;
  48. }else{
  49. high = mid - 1;
  50. }
  51. }
  52. }
  53. return -1;
  54.  
  55. }
  56. }
Success #stdin #stdout 0.09s 52636KB
stdin
Standard input is empty
stdout
Standard output is empty