leetCode第一題

leetCode第一題

普通解決思路

將數組變量兩次,相加判斷是否等於傳過來的值,如果等於,返回下標

自己寫的代碼,如果有錯誤請指出,謝謝

package com.leetcode.firstquestion.one;
import java.util.Arrays;
/**
* @program: test
* @description: 兩數之和 給定一個整數數組 nums 和一個目標值 target,
* 請你在該數組中找出和為目標值的那
* 兩個 整數,並返回他們的數組下標。
* @author: Mr.Yang
* @create: 2019-05-08 09:20
**/
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ints = new int[2];
int indexOne=0;
int indexTwo=0;
boolean flag=false;
for(int x=0;x<nums.length> for(int y=x+1;y<nums.length> if((nums[x]+nums[y])==target){
indexOne=x;
indexTwo=y;
flag=true;
break;
}
}
if(flag){
break;
}
}
ints[0]=indexOne;
ints[1]=indexTwo;
return ints;
}
public static void main(String[] args) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9};

Solution solution = new Solution();
int[] ints1 = solution.twoSum(ints, 9);
System.out.println(Arrays.toString(ints1));
}
}
/<nums.length>/<nums.length>

網上流傳思路,使用HashMap來處理

將數組的遍歷值當作key(為了存取好處理,所以將數組的遍歷值當作key),索引當作value來存儲。

package com.leetcode.firstquestion.two;
import java.util.Arrays;
import java.util.HashMap;
/**
* @program: test
* @description: 兩數之和 給定一個整數數組 nums 和一個目標值 target,
* 請你在該數組中找出和為目標值的那
* 兩個 整數,並返回他們的數組下標。
* @author: Mr.Yang
* @create: 2019-05-08 09:20
**/
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<object> argsMap = new HashMap<>();
for(int i=0;i<nums.length> int value = nums[i];
if(argsMap.containsKey(target - value)){
return new int[]{i, argsMap.get(target - value)};
}
argsMap.put(value,i);
}
return null;
}
public static void main(String[] args) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Solution solution = new Solution();
int[] ints1 = solution.twoSum(ints, 9);
System.out.println(Arrays.toString(ints1));

}
}
/<nums.length>/<object>
  • 相比較自己寫的那個確實要好得多,自己那個需要遍歷兩次,簡單時間複雜度O(n2)
  • 網上的方法,簡單時間複雜度O(n)
leetCode第一題

leetcode


分享到:


相關文章: