leetcode编程题(1)Two Sum

导言

leetcode是一个判断型的OJ,拥有大量的算法题目,最近拿来练手

题目(原题目)

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].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

题目中文翻译

给定一个整数数组,返回两个数的下标,使得它们加起来的特定目标数的数值。

你可以假设每个输入将有一个确切的解决方案。
例:

给定整型数组NUMS = [ 2 , 7 ,11,15 ] ,目标= 9 ,

由于NUMS [0] + NUMS [1] = 2 + 7 = 9,
返回[ 0,1 ] 。

更新日期( 2016年2月13日) :
返回格式已改为从零开始的索引。请仔细阅读上面的更新说明。

解析

由于题目说过,假设每一个输入都有一个解决方案,所以不必担心返回result为空,那么问题就来了。应该如何解决呢?

题目说返回两个数的下标,说明这两个数的下标必然不相等。

我们假设当前遍历的数字的下标为i,即将与其相加的数字下标为j,我们将数字i从0到NUMS.length-1,对于每一个NUMS[i]来说,不必考虑下标小于它的数字与其相加,因为如果i>1,那么在当前要相加数字的第一个数字下标在[0,i-1]的时候,就已经和i相加过了,而且不相等。

所以为了方便,我们采用两个下标来记录当前相加的两个数字的下标i,j。对于每一个i来说,从下标为[i+1,nums.length]之中在NUMS数组里选出一个数字,查看是否与其相加是否与目标数字相等,一旦相等便退出循环,然后将结果返回。

代码

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int []result = new int [2];
            for(int i=0;i<nums.length-1;i++)
                for(int j=i+1;j<nums.length;j++)
                {
                    if(nums[i]+nums[j] == target)
                    {
                        result[0]=i;
                        result[1]=j;
                        break;
                    }
                }

            return result;  
    }
}

测试的代码

package array;

public class leetcode1 {

        public int[] twoSum(int[] nums, int target) {

            int []result = new int [2];
            for(int i=0;i<nums.length-1;i++)
                for(int j=i+1;j<nums.length;j++)
                {
                    if(nums[i]+nums[j] == target)
                    {
                        result[0]=i;
                        result[1]=j;
                        break;

                    }
                }

            return result;          
        }

        public static void main(String[] args) {
            leetcode1 l = new leetcode1();
            int[] nums = {3,2,4};
            int []result = l.twoSum(nums, 6);
            System.out.println(result[0]+" "+result[1]);
        }
}

运行结果

这里写图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuYunTan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值