找出和为目标值的那 两个 整数

给定一个整数数组 nums 和一个目标值 target,在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。(题目来自力扣网站)

public class TowNumSum {
    public static int[] twoSum(int[] nums, int target) {
        int res[] = new int[2];
        for(int i = 0 ;i < nums.length; i++) {
            //System.out.println(i+"---"+nums.length);
            for (int j = i+1; j < nums.length; j++) {
                if(i == j)
                    continue;
                if ((nums[i] + nums[j]) == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }

暴力算法时间复杂度O(n^2)

发布了51 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/pannubi/article/details/94736613
今日推荐