leetcode笔记

1. Two Sum

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 num[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

Solution:

/*
利用HashMap的特性,把时间复杂度由O(n^2)降到O(n),敲黑板重点
*/
public class Solution{
  public int[] twoSum(int[] nums, int target){
    HashMap<Integer,Inteeger> tracker = new HashMap<Integer, Integer>();
    int len = nums.length;
    for(int i = 0; i < len; i++){
      if(tracker.containsKey(nums[i])){
        int left = tracker.get(nums[i]);
        return new int[]{left, i};
      }else{
        tracker.put(target - nums[i], i);
      }
    }
    return new int[2];
  }
}

2. 3Sum

Given an array s of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: the solution set must not contain duplicate triplets.
Example:

S = [-1, 0, 1, 2, -1, -4]
A solution set is:
[
  [-1, 0, 1],
  [-1, -1 ,2]
]

Solution:

/*
平均时间复杂度为O(n^2)
以递增的顺序对数组进行排序,遍历除最后两个元素的所有元素作为三元祖的第一个数,然后两头遍历数组,求的复合要求的第二个和第三个元素。
特别注意重复元素的剔除
*/
public class Solution{
    public List<List<Integer>> threeSum(int[] nums){
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            if(nums[i]>0) break;
            if(i==0||(i>0&&nums[i-1]!=nums[i])){
                int j=i+1;
                int k=nums.length-1;
                int num=-nums[i];
                while(j<k){
                    if(nums[j]+nums[k]==num){
                        res.add(Arrays.asList(nums[i],nums[j],nums[k]));
                        while(j<k&&nums[j]==nums[j+1]) j++;
                        while(j<k&&nums[k]==nums[k-1]) k--;
                        j++;
                        k--;
                    }else{
                        if(nums[j]+nums[k]<num) j++;
                        else k--;
                    }
                }
            }
        }
        return res;
    }
}

3. Valid Square

Given the coordinates of four points in 2D space, return whether the four points could construct a square The coordinate (x,y) of apoint is represented by an integer array with two integers.
Example

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4[0,1]
Output: True

Solution

/*
注意4个点位置相同的情况
*/
public class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        int s[]=new int[6];
        int k=0;
        List<Integer[]> list=new ArrayList<>();
        list.add(new Integer[]{p1[0], p1[1]});
        list.add(new Integer[]{p2[0], p2[1]});
        list.add(new Integer[]{p3[0], p3[1]});
        list.add(new Integer[]{p4[0], p4[1]});

        for(int i=0;i<3;i++){
            for(int j=i+1;j<4;j++){
                Integer[] a=list.get(i);
                Integer[] b=list.get(j);
                int tmp= (int) (Math.pow(a[0]-b[0],2)+Math.pow(a[1]-b[1],2));
                s[k]=tmp;
                int f=1;
                while(k-f>=0&&tmp<s[k-f]){
                    tmp=s[k-f+1];
                    s[k-f+1]=s[k-f];
                    s[k-f]=tmp;
                    f++;
                }
                k++;
            }
        }
        if(s[0]==s[1]&&s[1]==s[2]&&s[2]==s[3]&&s[4]==s[5]&&s[3]!=s[4])
            return true;
        else return false;
    }
}

3. Add Two Numbers

You are given two non-empty liked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution:

/*
此题解题思路比较常规,但是需要注意链表空值状态的判断,以及如何使得代码逻辑规整。
class Solution为我的解决方案,class Solution1为别人的解决方案
*/
public class Solution {
    public ListNode addTwoNumbers(ListNode l1,ListNode l2){
        if(l1==null) return l2;
        if(l1!=null&&l2==null) return l1;
        return add(l1,l2,0);
    }

    public ListNode add(ListNode l1,ListNode l2,int carry){
        int sum=l1.val+l2.val+carry;
        int c=0;
        if(sum>=0){
            c=sum/10;
            sum=sum%10;
        }
        ListNode node = new ListNode(sum);

        if(l1.next==null) {
            
            if(l2.next!=null){
                if(c==0)
                    node.next=l2.next;
                else
                    node.next=add(new ListNode(0),l2.next,c);
            }else
                if(c!=0)
                    node.next=add(new ListNode(0),new ListNode(0),c);
            return node;
        }
        else{
            if(l2.next==null) {
                if(c==0)
                    node.next = l1.next;
                else
                    node.next = add(l1.next, new ListNode(0), c);
            }else node.next=add(l1.next,l2.next,c);
            return node;
        }
    }

}

public class Solution1 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode prev = new ListNode(0);
        ListNode head = prev;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            ListNode cur = new ListNode(0);
            int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
            cur.val = sum % 10;
            carry = sum / 10;
            prev.next = cur;
            prev = cur;
            
            l1 = (l1 == null) ? l1 : l1.next;
            l2 = (l2 == null) ? l2 : l2.next;
        }
        return head.next;
    }
}

4. Longest Substring Without Repeating Characters

Given a string,find the length of the longest substring without repeating characters.
Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke",with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Solution:

  \*
利用HashMap减少时间复杂度,涉及到一组数据找一个数据时,应多思考HashMap来优化算法
*\
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len=s.length();
        if(len==0) return 0;
        int max=1;
        HashMap<Character,Integer> map=new HashMap<>();
        for(int i=0,j=0;i<len;i++){
            if(map.containsKey(s.charAt(i))){
                j=Math.max(map.get(s.charAt(i))+1,j);
            }
            map.put(s.charAt(i),i);
            max=Math.max(max,i-j+1);
        }
        return max;
    }
}

5.

import sun.swing.SwingUtilities2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 01sr on 2017/6/26.
 */
public class Sum {

    public static void main(String []args){
        new Sum().findMedianSortedArrays(new int[]{},new int[]{1});
    }
    /*
    *           left        |          right
    *  A[0],A[1]...,A[i-1]  |  A[i],A[i+1]...,A[m-1]
    *  B[0],B[1]...,B[j-1]  |  B[j],B[j+1]...,B[n-1]
    *  1)(i+j)*2=m+n+1;
    *  2)A[i-1]<=A[i],B[j-1]<=B[j](数组已排序,所以肯定满足);
    *  3)A[i-1]<=B[j],B[j-1]<=A[i];
    *
    *  由条件1)可以知道,当i确定时,j必然可以确定,所以控制i的变化就可以形成新的方案。设 i=0~m,则 j=(m+n+1)/2-i;
    *  条件3)可作为方案终止的判断条件;
    * */
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m=nums1.length;
        int n=nums2.length;
        if(m>n){
            int tmp=m;
            m=n;
            n=tmp;
            int[] tmps=nums1;
            nums1=nums2;
            nums2=tmps;
        }
        if(n==0)return -1;
        int mini=0,maxi=m,i=(mini+maxi)/2,j=(m+n+1)/2-i;
        while(mini<=maxi){
            i=(mini+maxi)/2;
            j=(m+n+1)/2-i;
            if(i>0&&nums1[i-1]>nums2[j]) maxi=i-1;

            else if(i<m&&nums2[j-1]>nums1[i]) mini=i+1;
                else{
                    int left=-1,right;
                    if(i==0) left=nums2[j-1];
                    else if(j==0) left=nums1[i-1];
                    else left=nums1[i-1]>nums2[j-1]?nums1[i-1]:nums2[j-1];

                    if((m+n)%2!=0) return left;

                    if(i==m) right=nums2[j];
                    else if(j==n) right=nums1[i];
                    else right = nums1[i] < nums2[j] ? nums1[i] : nums2[j];
                    return (left+right)/2.0;
                }
        }
        return -1;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,165评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,503评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,295评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,589评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,439评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,342评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,749评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,397评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,700评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,740评论 2 313
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,523评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,364评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,755评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,024评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,297评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,721评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,918评论 2 336

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,712评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,259评论 0 23
  • 透过陈旧的窗, 向远望 , 是那一望无际的黄。 热泪不知不觉地涌上眼眶, 浸润满目的荒凉, 模糊了远方。 休憩的半...
    过往城殇阅读 150评论 0 1
  • 表哥现在是一家国企的主管,他从小就是我的偶像,勤奋努力刻苦,记忆中的他从来就是一直优秀的那种人,从小学到大学...
    爱着成都的花少阅读 545评论 0 1
  • 直接插入排序 第一个元素就认为是有序的取第二个元素,判断是否大于第一个元素。若是大于,表示已经有序,不用移动,否则...
    muyang_js的简书阅读 149评论 0 0