萌新小白LeetCode之路——1.leetcode_Two Sum

萌新小白LeetCode之路——1.Two Sum

Leetcode專欄
Leetcode第一題(HashMap解法)
Leetcode第9題
Leetcode第21題

題目

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].
在數組nums中,取出你想得到的target,返回組成這兩個數的在數組中的位置

// two sum
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] slove = {0,0};
        for(int i=0;i<nums.length;i++)
        {
            for(int j=i+1;j<nums.length;j++) 
            //這裏我理解爲,數組中第一個與後面所有的都沒有
            //可以得到target,所以是從第i+1個開始
            {
                if(nums[i]+nums[j]==target)
                {
                    slove[0] = i;
                    slove[1] = j;
                    return slove;
                }
            }
        }
        return slove;         
    }
}

測試結果

圖片: 在這裏插入圖片描述

21.05%結果不是很高,不過第一題啦,只是一個開始

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章