Leetcode第一题详解

先看题目要求:

    /**
     * <pre>
     * Given an array of integers, find two numbers such that they add up to a specific target number.
     * The function twoSum should return indices of the two numbers such that they add up to the target,
     * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
     * are not zero-based.
     * You may assume that each input would have exactly one solution.
     *
     * Input: numbers={2, 7, 11, 15}, target=9
     * Output: index1=1, index2=2
     *
     * 题目大意
     * 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
     * 要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。

     * 请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。你可以假设每一个输入肯定只有一个结果。

新手,所以首先想到是暴力:

package mypackage;
public class Solution {
public String twoSum(int a[],int target){
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
if(a[i]+a[j]==target&&i!=j){
return "两个索引位置为  "+(i+1)+"   "+(j+1);
}
}
}
return "未找到这两个索引";
}

}

package mypackage;

public class Main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int a[]={3,2,1,4,5,6};
int target=5;
Solution s=new Solution();
System.out.println(s.twoSum(a, target));
}

}

结果:两个索引位置为  1   2

做完看别人的。。。

package remypackage;
import java.util.Arrays;
public class Solution {
public class Node implements Comparable<Node>{
private int val;
private int index;
public Node(int v,int i){
this.val=v;
this.index=i;
}
@Override
public int compareTo(Node o) {
return this.val-o.val;
}
}
public int[] twoSum(int a[],int target){
int[] result={0,0};
Node[] node=new Node[a.length];
for(int i=0;i<a.length;i++){
node[i]=new Node(a[i], i);
}
Arrays.sort(node);

int lowindex=0;
int highindex=a.length-1;

while(lowindex<highindex){
if(node[lowindex].val+node[highindex].val==target){
if(node[lowindex].index<node[highindex].index){
result[0]=node[lowindex].index+1;
result[1]=node[highindex].index+1;
}else{
result[0]=node[highindex].index+1;
result[1]=node[lowindex].index+1;
}
return result;
}else if(node[lowindex].val+node[highindex].val>target){
highindex--;
}else{
lowindex++;
}
}
return result;
}

}

package remypackage;
public class Main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int a[]={5,2,3,4,1,6};
int target=6;
Solution s=new Solution();
int result[]=s.twoSum(a, target);
System.out.println("["+result[0]+"  ,  "+result[1]+"  ]");
}

}

结果: [1  ,  5  ]

分析下 ,我的暴力没啥说的,遍历两遍,他的思想应该是定义高低索引值来扫数组,这样数组只被遍历可能不到一遍,但这样前提是有序,所以需要用个Arrays.sort排序,但排序后改变了原数组数据的位置(因为最后要返回索引),就需要定义Node来记录下原始数据的位置.其余不懂或有错的地方还请评论区留言噢。

猜你喜欢

转载自blog.csdn.net/qq_38813780/article/details/80525611
今日推荐