兩數之和(leetcode——java語言實現)

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
示例:

給定 nums = [2, 7, 11, 15], target = 9

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

 



/**
 * @author LLJ
 * @time 2020-6-23 下午10:19:39
 * @Description 兩數之和
 * 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
 * 你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
示例:

給定 nums = [2, 7, 11, 15], target = 9

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
 */
public class TwoNumberSum2 {
	public static void main(String[] args) {
	    int[] nums = {2,7,11,15};
            int target = 9;
            int[] twoSum = twoSum2(nums,target);
            for (int i = 0; i < twoSum.length; i++) {
		System.out.println(twoSum[i]);
	    }
	}
	
	/**
	 * 
	 * @Time 2020-6-23 下午10:40:46
	 * @param nums
	 * @param target
	 * @return 返回的是 2,7 【失誤的】,正確結果爲:0,1
	 */
	public static int[] twoSum(int[] nums, int target) {//返回和爲target的兩個數
	    int[] num = new int[2];//預先創建一個數組,準備存(和爲target的)兩個數
            int numb = 0;//定義一個數,初始化值爲0(當存入新數組時的下標)
            for(int i = 0;i < nums.length;i++){
                for(int j = i+1;j < nums.length;j++){//i+1:防止數字重複使用
                    if(nums[i] + nums[j] == target){//如果之和相等,則這兩個數就是要找的那兩個數,準備存入數組,並要最後返回
                        num[numb] = nums[i];//第一個數存入數組num,下標爲numb的初始值值0
                        num[numb+1] = nums[j];//第二個數存入數組num,下標爲numb的初始值0+1
                    }
                }
            }
            return num;
    }
	
	/**
	 * 
	 * @Time 2020-6-23 下午10:48:16
	 * @param nums
	 * @param target
	 * @return 返回結果爲:0,1【正確】
	 */
	public static int[] twoSum2(int[] nums, int target) {
	    int[] num = new int[2];//預先創建一個數組,準備存(和爲target的)兩個數
            int numb = 0;//定義一個數,初始化值爲0(當存入新數組時的下標)
            for(int i = 0;i < nums.length;i++){
                for(int j = i+1;j < nums.length;j++){//i+1:防止數字重複使用
                    if(nums[i] + nums[j] == target){//如果之和相等,則這兩個數就是要找的那兩個數,準備存入數組,並要最後返回
                        num[numb] = i;//第一個數的下標i存入數組num,下標爲numb的初始值值0
                        num[numb+1] = j;//第二個數的下標j存入數組num,下標爲numb的初始值0+1
                    }
                }
            }
            return num;
        }


}

 

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