我写的代码:
class Solution {
public int[] twoSum(int[] price, int target) {
int []array= new int [2];
int left=0;
int right=price.length-1;
while(left<right) {
if((price[left]+price[right])>target) {
right--;
}
if((price[left]+price[right])<target) {
left++;
}
if((price[left]+price[right])==target) {
array[0]=price[left];
array[1]=price[right];
break;
}
}
return array;
}
}
官方写的:
class Solution
{
public int[] twoSum(int[] nums, int target)
{
int left = 0, right = nums.length - 1;
while(left < right)
{
int sum = nums[left] + nums[right];
if(sum > target) right--;
else if(sum < target) left++;
else return new int[] {nums[left], nums[right]};
}
// 照顾编译器
return new int[]{0};
}
}