简单题56-两数之和

作者: Airycode | 来源:发表于2018-05-10 16:39 被阅读6次

    【题目】
    描述

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。

    你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1。
    你可以假设只有一组答案。
    您在真实的面试中是否遇到过这个题? 是
    样例

    给出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].
    挑战

    Either of the following solutions are acceptable:

    O(n) Space, O(nlogn) Time
    O(n) Space, O(n) Time
    【思路】
    两次循环数组求两个数的和是不是等于target
    【代码实现】

    package 两数之和;
    
    public class Main {
    
        public static void main(String[] args) {
            int [] arr = {2, 7, 11, 15};
            int target = 9;
            
            int [] result = twoSum(arr,target);
            
            print(result);
            
        }
        
        private static void print(int[] result) {
            for (int i=0;i<result.length;i++) {
                System.out.print(result[i]+" ");
            }
            System.out.println();
            
        }
    
        public static int[] twoSum(int[] numbers, int target) {
            int [] result = new int[2];
            for (int i=0;i<numbers.length;i++) {
                for (int j=i+1;j<numbers.length;j++) {
                    if (numbers[i]+numbers[j] == target) {
                        result[0] = i+1;
                        result[1] = j+1;
                    }
                }
            }
            return result;
        }
        
    }
    
    

    相关文章

      网友评论

        本文标题:简单题56-两数之和

        本文链接:https://www.haomeiwen.com/subject/hbqtdftx.html