Leetcode 1. Two Sum (java),leetcodesum

來源:互聯網
上載者:User

Leetcode 1. Two Sum (java),leetcodesum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

解法一:

class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if( nums[i] + nums[j] == target ){
int[] result = new int[2];
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}

使用了兩層迴圈進行遍曆,時間複雜度為O(n²)

解法二:

class Solution {
public int[] twoSum(int[] nums, int target) {
Hashtable<Integer,Integer> map = new Hashtable<Integer,Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i],i);
}
for (int i = 0; i < nums.length; i++) {
int another = target - nums[i];
       //過濾元素本身
if( map.get(another) != null &&map.get(another) > i ){
int[] result = new int[2];
result[0] = i;
result[1] = map.get(another);
return result;
}
}
return null;
}
}

使用了雜湊表進行尋找,時間複雜度為O(n)

 

解法一使用的是順序尋找,時間複雜度為O(n)

解法二使用的是雜湊尋找,時間複雜度為O(1)

此外常用的尋找:二分尋找O(logn),二叉排序尋找法O(logn),分塊尋找O(logn)

 

github地址:https://github.com/CyanChan/Leetcode-Record

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.