面试题57. 和为s的两个数字
程序员文章站
2024-03-04 11:34:35
...
题目:
题解:
代码:
/**
* 面试题57
*/
public class 面试题57 {
public static int[] twoSum(int[] nums, int target) {
int i = 0;
int j = nums.length - 1;
while(i < j)
{
int sum = nums[i] + nums[j];
if(sum < target)
{
i++;
}
else if(sum > target)
{
j--;
}
else if(sum == target)
{
// int res[] = new int[2];
// res[0] = nums[i];
// res[1] = nums[j];
int res[] = { nums[i], nums[j] }; // 长度为2的数组
return res;
}
}
int res[] = new int[0]; // 空数组
return res;
}
public static void main(String[] args) {
int nums[] = { 10, 26, 30, 31, 47, 60 };
int target = 40;
int ans[] = twoSum(nums, target);
for(int i = 0; i < ans.length; i++)
{
System.out.print(ans[i] + " ");
}
System.out.println();
}
}