本节内容
二分搜索; 两数之和:输入一个已按照升序排列的有序数组nums和一个目标值target,在nums中找到两个数使得它们相加之和等于target,请返回这两个数的索引; 反转数组。
代码与解读
package com. company;
import static java. lang. System. out;
import java. util. *;
public class Main {
public static int binarySearch ( int [ ] nums, int target) {
int left = 0 ;
int right = nums. length - 1 ;
while ( left <= right) {
int mid = ( left + right) / 2 ;
if ( nums[ mid] == target)
return mid;
else if ( target < nums[ mid] )
right = mid - 1 ;
else
left = mid + 1 ;
}
return - 1 ;
}
public static int [ ] twoSum ( int [ ] nums, int target) {
int left = 0 ;
int right = nums. length - 1 ;
while ( left < right) {
int sum = nums[ left] + nums[ right] ;
if ( sum == target)
return new int [ ] { left + 1 , right + 1 } ;
else if ( sum < target)
left++ ;
else
right-- ;
}
return new int [ ] { - 1 , - 1 } ;
}
public static void reverse ( int [ ] nums) {
int left = 0 ;
int right = nums. length - 1 ;
while ( left < right) {
int temp = nums[ left] ;
nums[ left] = nums[ right] ;
nums[ right] = temp;
left++ ; right-- ;
}
}
public static void main ( String[ ] args) {
int [ ] nums = { 1 , 2 , 3 , 4 , 5 } ;
int target = 3 ;
int res1 = binarySearch ( nums, target) ;
out. println ( res1) ;
int [ ] res2 = twoSum ( nums, target) ;
out. println ( res2[ 0 ] + ", " + res2[ 1 ] ) ;
reverse ( nums) ;
for ( int i : nums) {
out. println ( i + " " ) ;
}
}
}
如果你认为对你有用,关注我的微信公众号支持我一下吧!~