leetcode:java中的數組操作

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].



一個數組,一個數字,如果這個數字爲數組中任意兩個元素之和,那麼給出這兩個元素的位置索引。


public class Solution {

    public int[] twoSum(int[] nums, int target) {

        //定義一個空數組,爲儲存返回值備用

        int[] result =new int[2];

        //開始遍歷數組

        for (int i=0;i<nums.length;i++){

            

            int one = target - nums[i];

                //每次比較只需向後即可

                for (int m = i + 1; m < nums.length; m++){

                    

                    if (nums[m] == one){

                         result[0] = i;

                         result[1] = m;

                         return result;

                    }

                    

                }

        }

    //在for循環的外面需要一個返回值,如果循環無法正常運行,方法也需要一個返回值。

    return null;

    }

}


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