2023年8月23日 星期三

【LeetCode】【Kotlin】1. Two Sum (IntArray、Brute Force、 Hash Table )

 Brute Force 

  1. class Solution {
  2. fun twoSum(nums: IntArray, target: Int): IntArray {
  3. for (i in 0..nums.size-1){
  4. for (j in i+1..nums.size-1){
  5. if (nums[i] + nums[j] == target) {
  6. return intArrayOf(i , j)
  7. }
  8. }
  9. }
  10. return intArrayOf()
  11. }
  12.  
  13. }

Two-pass Hash Table

  1. class Solution {
  2. fun twoSum(nums: IntArray, target: Int): IntArray {
  3. var hashmap: MutableMap<Int, Int> = mutableMapOf()
  4. for(i in 0..nums.size-1){
  5. hashmap.put(nums[i], i)
  6. }
  7. for(i in 0..nums.size-1){
  8. val complement = target - nums[i]
  9. if(hashmap[complement] != null && hashmap[complement] != i){
  10. return intArrayOf(i, hashmap[complement] ?: -1)
  11. }
  12. }
  13. return intArrayOf()
  14. }
  15.  
  16. }

One-pass Hash Table

  1. class Solution {
  2. fun twoSum(nums: IntArray, target: Int): IntArray {
  3. var hashmap: MutableMap<Int, Int> = mutableMapOf()
  4. for(i in 0..nums.size-1){
  5. val complement = target - nums[i]
  6. if(hashmap[complement] != null && hashmap[complement] != i){
  7. return intArrayOf(i, hashmap[complement] ?: -1)
  8. }
  9. hashmap.put(nums[i], i)
  10. }
  11.  
  12. return intArrayOf()
  13. }
  14. }
算出數字與目標值差多少,若表中存在所需要的值,就可以從表中查到該值所在位址。
若表中沒有,就把自己的數值與位置存入表中(將位置的值放在index=自己的數值)。

0 comments:

張貼留言