classSolution { funcsearchInsert(_nums: [Int], _target: Int) -> Int { var left =0 var right = nums.count -1 while left <= right { let mid = left + (right - left) /2 if nums[mid] == target { return mid } elseif nums[mid] < target { left = mid +1 } else { right = mid -1 } } return left } }
结果
执行用时 : 10 ms, 击败 99.43% 使用 Swift 的用户
内存消耗 : 15.36 MB, 击败 36.93% 使用 Swift 的用户
Kotlin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { funsearchInsert(nums: IntArray, target: Int): Int { var left = 0 var right = nums.size - 1 while (left <= right) { val mid = left + (right - left) / 2 when { nums[mid] == target -> return mid nums[mid] < target -> left = mid + 1 else -> right = mid - 1 } } return left } }
结果
执行用时 : 190 ms, 击败 25.30% 使用 Kotlin 的用户
内存消耗 : 38.00 MB, 击败 22.89% 使用 Kotlin 的用户
Dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution{ int searchInsert(List<int> nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + ((right - left) ~/ 2); if (nums[mid] == target) { return mid; } elseif (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return left; } }
结果
执行用时 : 334 ms, 击败 17.65% 使用 Dart 的用户
内存消耗 : 147.11 MB, 击败 70.59% 使用 Dart 的用户
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcsearchInsert(nums []int, target int)int { left, right := 0, len(nums)-1 for left <= right { mid := left + (right-left)/2 if nums[mid] == target { return mid } elseif nums[mid] < target { left = mid + 1 } else { right = mid - 1 } } return left }
结果
执行用时 : 0 ms, 击败 100.00% 使用 Go 的用户
内存消耗 : 2.84 MB, 击败 5.00% 使用 Go 的用户
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# @param {Integer[]} nums # @param {Integer} target # @return {Integer} defsearch_insert(nums, target) left, right = 0, nums.length - 1 while left <= right mid = left + (right - left) / 2 if nums[mid] == target return mid elsif nums[mid] < target left = mid + 1 else right = mid - 1 end end return left end
结果
执行用时 : 68 ms, 击败 37.50% 使用 Ruby 的用户
内存消耗 : 206.66 MB, 击败 25.00% 使用 Ruby 的用户
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
objectSolution{ defsearchInsert(nums: Array[Int], target: Int): Int = { var left = 0 var right = nums.length - 1 while (left <= right) { val mid = left + (right - left) / 2 if (nums(mid) == target) { return mid } elseif (nums(mid) < target) { left = mid + 1 } else { right = mid - 1 } } left } }
结果
执行用时 : 481 ms, 击败 90.91% 使用 Scala 的用户
内存消耗 : 54.70 MB, 击败 9.09% 使用 Scala 的用户
Rust
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
implSolution { pubfnsearch_insert(nums: Vec<i32>, target: i32) ->i32 { letmut left = 0; letmut right = nums.len() asi32 - 1; while left <= right { letmid = left + (right - left) / 2; if nums[mid asusize] == target { return mid; } elseif nums[mid asusize] < target { left = mid + 1; } else { right = mid - 1; } } left } }