Guest User

Untitled

a guest
Jul 23rd, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. /**
  2. * Given an array of integers, find two numbers such that they add up to a specific target numbers.
  3. * The function twoSum should return indices of the two numbers such that they add up to the target,
  4. * where index1 must be less than index2. Please note that your returned answers(both index1 and index2)
  5. * are not zero-based.
  6. *
  7. * You may assume that each input would have exactly one solution.
  8. *
  9. * Input: 2, 7, 11, 15 9
  10. * Output: 1, 2
  11. * Idea: (1) 方法1,两个循环,复杂度O(n2)
  12. * (2) 方法2,空间换时间,用hashmap来缓存数据,复杂度O(n)
  13. */
  14. fun twoSum(array: Array<Int>, target: Int) : Array<Int> {
  15. if (array.size < 2) {
  16. return arrayOf(0, 0)
  17. }
  18.  
  19. val map = hashMapOf<Int, Int>()
  20. for (i in 0 until array.size) {
  21. if (map.contains(array[i])) {
  22. return arrayOf(map[array[i]]!! + 1, i + 1)
  23. } else {
  24. map[target - array[i]] = i
  25. }
  26. }
  27. return arrayOf(0, 0)
  28. }
Add Comment
Please, Sign In to add comment