zoukankan      html  css  js  c++  java
  • Two Sum

    题目

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    方法

    简单的双重循环就可以。
    	    public int[] twoSum(int[] numbers, int target) {
    	        int len = numbers.length;
    	        int[] index = new int[2];
    	        for(int i = 0; i < len - 1; i++){
    	            int num1 = numbers[i];
    	            for(int j = i + 1; j < len; j++){
    	                int num2 = numbers[j];
    	                if(num1 + num2 == target){
    	                    index[0] = i + 1;
    	                    index[1] = j + 1;
    	                    i = len;
    	                    j = len;
    	                }
    	            }
    	        }
    	        return index;
    	    }


  • 相关阅读:
    JS制作图表
    把图片存入数据库
    .NET各种小问题
    JS各种小问题
    JS操作cookie
    JS处理Json数据
    git与svn的区别
    关于java中的一些循环
    java基础面试(上)
    Spring事务
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5143344.html
Copyright © 2011-2022 走看看