Brute Force
- class Solution {
- fun twoSum(nums: IntArray, target: Int): IntArray {
- for (i in 0..nums.size-1){
- for (j in i+1..nums.size-1){
- if (nums[i] + nums[j] == target) {
- return intArrayOf(i , j)
- }
- }
- }
- return intArrayOf()
- }
- }
Two-pass Hash Table
- class Solution {
- fun twoSum(nums: IntArray, target: Int): IntArray {
- var hashmap: MutableMap<Int, Int> = mutableMapOf()
- for(i in 0..nums.size-1){
- hashmap.put(nums[i], i)
- }
- for(i in 0..nums.size-1){
- val complement = target - nums[i]
- if(hashmap[complement] != null && hashmap[complement] != i){
- return intArrayOf(i, hashmap[complement] ?: -1)
- }
- }
- return intArrayOf()
- }
- }
One-pass Hash Table
- class Solution {
- fun twoSum(nums: IntArray, target: Int): IntArray {
- var hashmap: MutableMap<Int, Int> = mutableMapOf()
- for(i in 0..nums.size-1){
- val complement = target - nums[i]
- if(hashmap[complement] != null && hashmap[complement] != i){
- return intArrayOf(i, hashmap[complement] ?: -1)
- }
- hashmap.put(nums[i], i)
- }
- return intArrayOf()
- }
- }
若表中沒有,就把自己的數值與位置存入表中(將位置的值放在index=自己的數值)。
0 comments:
張貼留言