LeetCode Two sum

LeetCode的第一题

Two Sum
Total Accepted: 309644
Total Submissions: 1145736
Difficulty: Easy
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].
给的解释太少,又因为是第一次在这做题,闹了一些笑话。
看完题后,想着用最笨的办法,很简单,自己写main函数,用上给的接口。但对于题目给的输入没搞明白,以为是字符串,需要自己将数字提取转换为整数数组,最后还要把结果再转换为字符串输出。才学java,对于字符串转化啥的也不是很了解。上网查了半天终于弄好了,提交却怎么也不正确。百度了一下LeetCode的检测原理才知道,只需要把接口写好就行,根本不要什么字符串转换。咳咳咳。。。
字符串转换版的(比较渣):

package test_1;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    /*public int[] twoSum(int[] nums, int target) {
        for (int i=0; i<nums.length-1; i++){
            for (int j=i+1; j<nums.length; j++){
                if (nums[i]+nums[j] == target){
                    int[] b = {i,j};

                    return b;
                }         
            }
        }
        return null;
    }*/
    public int[] twoSum(String nums, int target) {

        int[] a = new int[nums.length()];
        for (int i=0; i<nums.length(); i++){
            a[i] = nums.charAt(i)-'0';
        }
        //System.out.println(a[0]);
        for (int i=0; i<a.length-1; i++){
            for (int j=i+1; j<a.length; j++){
                if (a[i]+a[j] == target){
                    int[] b = {i,j};
                    return b;
                }             
            }
        }
        return null;
    }
    public static void main(String[] args){
        Test s = new Test();
        Scanner in = new Scanner(System.in);
        String array = in.next();
        int target = in.nextInt();
        //int[] a = new int[array.length()/2];
        String a = new String();

        //System.out.println(array);
        for (int i=0; i<array.length(); i++){
            if (array.charAt(i) <= '9' && array.charAt(i)>='0'){
                a += array.charAt(i);
            }
        }
        System.out.println(
                Arrays.toString(s.twoSum(new String(a), target)));       
    }
}

最终提交结果:
“`
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i=0; i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值