从2019年1月13日开始,争取每天学习一点算法知识,并且在优快云上记录,以防自己偷懒,主要的学习材料是Algorithm 4th 和leetcode, 当然是从最基础的内容开始学习啦。
问题描述:两数之和问题,使用JAVA实现。
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:
第一种解法:
1,代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
int[] output=new int[2];
int i=0,j=1;
for(;i<n;i++)
for(j=i+1;j<n;j++)
{
if(nums[i]+nums[j]==target)
{
output[0]=i;
output[1]=j;
return output;
}
}
return null;
}
}
2,运行效率:
第二种解法:采用了HashMap以空间换时间的方法来解决,有关于HashMap的问题可以参考
https://www.cnblogs.com/chengxiao/p/6059914.html 这个网址中已经解释的非常详细。
使用hash后,在理想情况下,查找的复杂度由O(n)降低到了O(1)。
1,代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
Map<Integer, Integer>hash_map=new HashMap<>();
for(int j=0;j<n;j++)
hash_map.put(nums[j],j);
int[] output=new int[2];
for(int i=0;i<n;i++)
{
int leftover=target-nums[i];
if(hash_map.containsKey(leftover)&&hash_map.get(leftover)!=i)
{
output[0]=i;
output[1]=hash_map.get(leftover);
return output;
}
}
return null;
}
}
2,运行时间
3,说明:
首先是将以值为key,对应的索引作为value存入到hashmap中,使用put函数将nums中的内容加入到hash_map中,之后查找另外一半值是否在hashmap中,且不能重复。
第三种解法,直接运行答案给出的最优解,使得运行时间更短,时间开销下降了一半
1,代码:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
2,运行结果
问题描述:利用NodeList进行加法运算,JAVA语言,leetcode第二题
1,代码(基本和官网答案一样)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode Head= new ListNode(0);
ListNode p=l1, q=l2,current=Head;
int carry=0;
while(p!=null||q!=null)
{
int x=(p!=null)? p.val:0;
int y=(q!=null)? q.val:0;
int sum=x+y+carry;
carry=sum/10;
current.next=new ListNode(sum%10);
current=current.next;
if(p!=null)
p=p.next;
if(q!=null)
q=q.next;
}
if(carry>0)
{
current.next=new ListNode(carry);
}
return Head.next;
}
}
2,运行结果