LeetCode答题记录--两数之和

这是在LeetCode刷的第一题,记录一下

思路是通过两个for循环对数组进行遍历,找出需要的数字,第一次提交时出错,后面增添了一条判断i与j是否相等的条件,最终成功提交

附上代码:
public class Solution {

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

    int[] result = new int[2];

    for (int i = 0; i < nums.length; i++) {

        int a = nums[i];

        for (int j = 1; j < nums.length; j++) {

            if (j==i){
                continue;
            }
            int b = nums[j];

            if (a + b == target) {

                result[0] = i;
                result[1] = j;

                return result;
            }
        }

    }

    return null;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42857414/article/details/88557464