zoukankan      html  css  js  c++  java
  • leetcode day8

    【83】 Remove Duplicates from Sorted List

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    For example,
    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.

    思路: 使用一个临时指针next来进行while循环链表,当碰到相同的值时,指针的指针域指向next.next.next向前推进 ,如果碰到不同的,则next = next.next,让next等于当前不同的新节点。使用迭代和递归的时间复杂度是一样的‘

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head==null||head.next==null){
                return head;
            }
            /*//recursive way
            head.next = deleteDuplicates(head.next);
            return head.val == head.next.val ? head.next : head;*/
            
            //iterative way
             ListNode node = head;
            while(node.next!=null){
              if(node.val==node.next.val){
                  node.next = node.next.next;
              }else{
                  node = node.next;
              } 
             }
            return head;
            
        }
    }

    【70】Climbing Stairs

    You are climbing a stair case. It takes n steps to reach to the top.

    Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

    思路:这个是斐波那契数列问题,只是前两个数是1、2.最好别用斐波那契额递归,时间会超出限制,用数组处理,只需明白思想是,后个数是前两个数的和

    public class Solution {
    
    public int climbStairs(int n) {
        if(n == 0 || n == 1 || n == 2){return n;}
        int[] mem = new int[n];
        mem[0] = 1;
        mem[1] = 2;
        for(int i = 2; i < n; i++){
            mem[i] = mem[i-1] + mem[i-2];
        }
        return mem[n-1];
    }
    }
  • 相关阅读:
    复利计算器2.01
    复利计算器2.0
    0429团队3.0
    0428 团队项目合作2.0作业
    "数学口袋精灵"bug
    操作系统-实验2
    博客评论
    复利计算升级
    0408 结对合作
    0406复利计算5.0
  • 原文地址:https://www.cnblogs.com/lucky-star-star/p/5005808.html
Copyright © 2011-2022 走看看