原题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
对于一个给定的整数数组和一个目标值,求出数组中两个数之和等于目标值,输出数组中这两个数的下标
算法分析:
算法1.时间复杂度为O(n^2).
采用两个指针i和j,i和j分别指向数组中前两个值,判断i和j所指值之和是否等于目标函数,若不等于,则向后移动i和j,直到找到两个数之和等于目标函数为止。输出i和j即可
遇到问题及解决方案:
1.没有考虑目标值是0的情况
如果直接判断两个数相加的值是否等于目标值,则会忽略目标值为0,数组中也同样包含0的情况,所有需要先判断目标值是否为0。
如果目标值为0,则直接找出两个0并输出即可。
if(target == 0 && nums[i] == 0&&nums[j] == 0){
tmp[0] = i;
tmp[1] = j;
return tmp;
}
LeetCode提交源码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null )
return null;
int[] tmp = new int[2];
// int i = 0;
// int j = 0;
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++){
if(target == 0 && nums[i] == 0&&nums[j] == 0){
tmp[0] = i;
tmp[1] = j;
return tmp;
}
if(nums[i] + nums[j] == target){
tmp[0] = j;
tmp[1] = i;
}
}
}
System.out.println(tmp[0] + " " + tmp[1]);
return tmp;
}
}
Submission Details:
完整运行程序:
package org.GuoGuoFighting.LeetCode1;
import java.util.Scanner;
class Solution1{
public int[] twoSum(int[] nums,int target){
if(nums == null )
return null;
int[] tmp = new int[2];
// int i = 0;
// int j = 0;
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++){
// if(nums[j] == target && nums[i] == target && i != j){ //如果输入的target包含在数组中,则返回这两个值
if(target == 0 && nums[i] == 0&&nums[j] == 0){ //如果输入的target包含在数组中,则返回这两个值
tmp[0] = i;
tmp[1] = j;
return tmp;
}
if(nums[i] + nums[j] == target){
tmp[0] = i;
tmp[1] = j;
}
}
}
System.out.println(tmp[0] + " " + tmp[1]);
return tmp;
}
}
public class TwoSum {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整形数组,用空格隔开:");
String str = scanner.nextLine();
System.out.println("请输入要找的目标k:");
int k = scanner.nextInt();
String[] tmp = str.split(" ");
int[] arrays = new int[tmp.length];
for(int i = 0; i < arrays.length;i++){
arrays[i] = Integer.parseInt(tmp[i]);
}
scanner.close();
Solution1 solution1 = new Solution1();
int[] ansarray = solution1.twoSum(arrays, k); //将输出的数组打印
System.out.println("这两个数是:" + ansarray[0] + "," + ansarray[1]);
}
}
程序运行结果: