classSolution { publicintsearch(int[] nums, int target) { intleft=0, right = nums.length - 1; while (left <= right) { intmid= (right - left) / 2 + left; intnum= nums[mid]; if (num == target) { return mid; } elseif (num > target) { right = mid - 1; } else { left = mid + 1; } } return -1; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution { publicintSearch(int[] nums, int target) { int left = 0, right = nums.Length - 1; while (left <= right) { int mid = (right - left) / 2 + left; int num = nums[mid]; if (num == target) { return mid; } elseif (num > target) { right = mid - 1; } else { left = mid + 1; } } return-1; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intsearch(vector<int>& nums, int target){ int left = 0, right = nums.size() - 1; while(left <= right){ int mid = (right - left) / 2 + left; int num = nums[mid]; if (num == target) { return mid; } elseif (num > target) { right = mid - 1; } else { left = mid + 1; } } return-1; } };
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var search = function(nums, target) { let left = 0, right = nums.length - 1; while (left <= right) { const mid = Math.floor((right - left) / 2) + left; const num = nums[mid]; if (num === target) { return mid; } elseif (num > target) { right = mid - 1; } else { left = mid + 1; } } return -1; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcsearch(nums []int, target int)int { left, right := 0, len(nums)-1 for left <= right { mid := (right-left)/2 + left num := nums[mid] if num == target { return mid } elseif num > target { right = mid - 1 } else { left = mid + 1 } } return-1 }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defsearch(self, nums: List[int], target: int) -> int: left, right = 0, len(nums) - 1 while left <= right: mid = (right - left) // 2 + left num = nums[mid] if num == target: return mid elif num > target: right = mid - 1 else: left = mid + 1 return -1