1.Two Sum(两数之和)

题目:
Two Sum
描述:
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, and you may not use the same element(元素) twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

来源:leetcode

分析:
题目大意:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

解答:直接暴力,无话可说

public int[] twosum(int[] arr,int target){
   
	for(int i=0;i<arr.length;i++){
   
		for(int j=i+1;j<arr.length;j++){
   
		if(arr[i]+arr[j] == target)
			return new int[]{
   i,j};
			}
		}
		throw new IllegalArgumentException("No two sum solution");
	}

解法(与一相同,不同的输出形式而已):

 for (int i = 0; i <nums.length ; i++) {
   
            for (int j = i+1; j <nums.length ; j++) {
   
                if (nums[i]+nums[j]==target){
   
                    a=i;
                    b=j;
                }
            }

        }
        System.out.println('['+a+','+b+']');
    }

tips:所有代码段均是在idea编译器测试通过!

全部评论

相关推荐

05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务