GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — AlgorithmNuggets/ProblemSolving/binarySearch/bin.py at master · srixivas/AlgorithmNuggets Expand file tree/ Copy pathbin.pyMore file actions 85 lines (71 loc) · 2.47 KB / Copy pathbin.pyFile metadata and controls85 lines (71 loc) · 2.47 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # Binary search is Half n Half. # * Always check for half and choose most promising # 2 pointer technique - to memorize the indexes as we move through the array without altering the array to perform the search should be apt... # Init left = 0 right = len(nums)-1 # Dividing by 2 and setting pointers as we proceed while left < right: mid = (left + right)//2 print left, mid, right if nums[mid] == target: return mid elif nums[mid] < target: left = mid else: right = mid # Smallest array condition (when the array is of length 2) if (right - left) == 1: if nums[right] == target: return right elif nums[left] == target: return left else: return -1 # Equal or single element condition if left == right and nums[left] == target: return left # no match condition return -1 """ # Binary search works in the below logic, existence returned # * Maintaining the index is not done here while nums: n = len(nums) mid = n//2 if nums[mid] == target: return True elif nums[mid] < target: nums = nums[mid:] else: nums = nums[:mid] return False """ """" # Altering same logic as above (for existence to crack) # * Maintaining the index left and right is a challenge start_index = 0 if nums[start_index] == target: return 0 while len(nums) > 1: n = len(nums) mid = n//2 if nums[mid] == target: if (start_index + mid) < start_index: return start_index - mid - 1 else: return start_index + mid elif nums[mid] < target: nums = nums[mid:] else: nums = nums[:mid] start_index += mid return -1 """ |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |