leetcode (1) 两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:

给定 nums = [2, 7, 11, 15], target = 9
 因为 nums[0] + nums[1] = 2 + 7 = 9
 所以返回 [0, 1]

思路: 我看到这个题目,我就想怎么使这个数组元素两两相加,两个for 循环这个数组,让这个数组元素和这个数组所有元素相加,但是会有相同的元素相加的不符合题意的。


//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 
//
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 
//
// 
//
// 示例: 
//
// 给定 nums = [2, 7, 11, 15], target = 9
//
//因为 nums[0] + nums[1] = 2 + 7 = 9
//所以返回 [0, 1]
// 
// Related Topics 数组 哈希表 
// 👍 8759 👎 0

package com.cute.leetcode.editor.cn;
public class TwoSum {
    public static void main(String[] args) {
        Solution solution = new TwoSum().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        //让数组元素两两相加 等于 target
        int[] result = new int[2];
        boolean tag = false;
        for(int i = 0 ; i < nums.length; i ++ ){
            int a = nums[i];
            for(int j = 0 ; j < nums.length ; j++){
                if(i==j){
                    continue;
                }
                int b = nums[j];
                int sum =a+b;
                if(sum==target){
                    result[0]=i;
                    result[1]=j;
                    tag = true;
                    break;
                }
            }

            if(tag){
                break;
            }
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}

  但是效率似乎不太好,下一张改进或换一种方法。

 

posted @ 2020-07-29 18:00  星辰忧沙  阅读(152)  评论(0编辑  收藏  举报