Search in Rotated Sorted Array II

来源:互联网 发布:联想电脑数据恢复 编辑:程序博客网 时间:2024/06/03 10:24

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

public class Solution {    public boolean search(int[] nums, int target) {    if(nums.length == 0 || nums == null){              return false;          }          int s = 0;          int e = nums.length -1;          int m = 0;          while(s+1<e){              m = s + (e-s)/2;              if(nums[m] == target){                  return true;              }else if(nums[s]<nums[m]){//左边全升序                  if(nums[s]<=target&&target<=nums[m]){//t在s,m之间                      e = m;//缩小范围                  }else{                      s = m;//去右边找                  }              }else if(nums[s] > nums[m]){//左边有转折点                  if(nums[m]<=target&&target<=nums[e]){//t在m,e之间                      s = m;//缩小范围                  }else{                      e = m;//去左边找                  }              }else{                s++;            }          }          if(nums[s] == target){              return true;          }          if(nums[e] == target){              return true;          }          return false;      }  }

haha...

public class Solution {    public boolean search(int[] nums, int target) {        for (int i = 0; i < nums.length; i ++) {            if (nums[i] == target) {                return true;            }        }        return false;      }  }


0 0
原创粉丝点击