zoukankan      html  css  js  c++  java
  • 给定数组和某个值,求和等于某值的序号

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

    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的方式进行选择;

     

  • 相关阅读:
    logback
    GC
    常用JVM配置参数
    JVM
    linux
    简单的webService 实例
    [转载]Java 工程师成神之路
    ActiveMQ 在mac 上的安装与运行
    subline3 + emmet 加快前端开发效率
    Spring WebMVC 4.1.4返回json时导致的 406(Not Acceptable)
  • 原文地址:https://www.cnblogs.com/stono/p/9446164.html
Copyright © 2011-2022 走看看