其他分享
首页 > 其他分享> > 给定数组和某个值,求和等于某值的序号

给定数组和某个值,求和等于某值的序号

作者:互联网

给定数组和某个值,求和等于某值的序号

给定数组和某个值,求和等于某值的序号

package com.test;

import java.util.Arrays;

/**
 * @author stono
 * @date 20180808
 * 1 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].
 */
public class Lesson001 {
    public static void main(String[] args) {
        int[] ints = {2, 7, 11, 15};
        int target = 9;

        getIndicesByArrayAndTarget(ints, target);
    }

    private static void getIndicesByArrayAndTarget(int[] ints, int target) {
        System.out.println("input:" + Arrays.toString(ints));
        int length = ints.length;
        for (int i = 0; i < length; i++) {
            for (int j=0;j<length;j++) {
                // i==j不能进行判断
                if (i - j == 0) {
                    continue;
                }
                // 强制循环两次
                int res = ints[i] + ints[j] - target;
                if (res == 0) {
                    System.out.println("output:"+i+";"+j);
                }
            }

        }
    }
}

 应该用map的方式进行选择;

 

 

标签:target,nums,int,某值,length,给定,ints,序号
来源: https://blog.51cto.com/u_15241951/2869562