zoukankan      html  css  js  c++  java
  • LeetCode(Java版)因为用上了MD所有删掉了以前的帖子

    第一题:

    //思路1.就不说了 时间复杂度 N^2
    //思路2.空间换时间 改题目没有限制空间 则 最优选   时间复杂度 N
    class Solution {
        public int[] twoSum(int[] nums, int target) {
         //用于存放 对比值
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            int[] result = new int[2];
            //遍历数组
            for (int i = 0; i < nums.length; i++) {
           //若本次遍历的值在 hashMap中存在一个 与之和与 target 相等的数则直接 return 
                if (map.containsKey(target - nums[i])) {
                    result[0] = map.get(target - nums[i]);
                    result[1] = i;  // 此时 i 对应的元素还没有放进去。
                    return result;
                }
           //若不存在 则 直接存入 等待下一次的比对   
                map.put(nums[i], i);
            }
            return result;
        }
    }
    

    第二题:

    /**
     * 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) {
            return addTwoNumbers(l1, l2, null);
        }
        public ListNode addTwoNumbers(ListNode l1, ListNode l2, ListNode prev) {
            ListNode next1 = null;
            ListNode next2 = null;
            int val1 = 0;
            int val2 = 0;
            if (l1 != null) {
                val1 = l1.val;
                next1 = l1.next;
            }
            if (l2 != null) {
                val2 = l2.val;
                next2 = l2.next;
            }
            ListNode newNode = new ListNode(val1 + val2);
            if (prev != null) {
                if (prev.val >= 10) {
                    prev.val %= 10;
                    newNode.val += 1;
                }
            }
            if (next1 != null || next2 != null) {
                newNode.next = addTwoNumbers(next1, next2, newNode);
            } else if (newNode.val >= 10) {
                newNode.next = addTwoNumbers(next1, next2, newNode);
            }
            return newNode;
        }
    }
    
  • 相关阅读:
    MySQL全文索引应用简明教程
    web前端的春天 or 噩梦
    [DeviceOne开发]-手势动画示例分享
    [DeviceOne开发]-土地销售项目源码分享
    [DeviceOne开发]-do_LinearLayout组件使用技巧
    2016年我们重新思考移动互联网创业的风险, 微信还是APP?
    APP技术演化的路
    ReactNative&weex&DeviceOne对比
    what's deviceone
    APP开放源码第一弹《纳豆》
  • 原文地址:https://www.cnblogs.com/shundong106/p/11188984.html
Copyright © 2011-2022 走看看