zoukankan      html  css  js  c++  java
  • LeetCode

    1.两数之和

    给定 nums = [2, 7, 11, 15], target = 9
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    public static int[] twoSum(int[] nums, int target) {
    		for(int a = 0 ;a < nums.length; a++) {
    			for(int b = a+1 ;b < nums.length; b++) {
    				int num = nums[a]+nums[b];
    				if(num == target) {
    					return new int[] { a, b };
    				}
    			}
    		}
    		//表明向方法传递了一个不合法或不正确的参数
    		throw new IllegalArgumentException("No two sum solution");
    	}
    
    
    public static void main(String[] args) {
    		int[] nums = {2, 5, 5, 11};
    		int[] res = twoSum(nums,13);
    		for (int i = 0; i < res.length; i++) {
    			System.err.println("对应的值:"+nums[res[i]]+"对应标:"+res[i]);
    		}
    	}
    

    2.两数想加

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    		ListNode dummyHead = new ListNode(0);
    		ListNode p = l1, q = l2, curr = dummyHead;
    		int carry = 0;
    		while (p != null || q != null) {
    			int x = (p != null) ? p.val : 0;
    			int y = (q != null) ? q.val : 0;
    			int sum = carry + x + y;
    			carry = sum / 10;
    			curr.next = new ListNode(sum % 10);
    			curr = curr.next;
    			if (p != null) p = p.next;
    			if (q != null) q = q.next;
    		}
    		if (carry > 0) {
    			curr.next = new ListNode(carry);
    		}
    		return dummyHead.next;
    	}
    
    
    public static void main(String[] args) {
    		//设置参数1
    		ListNode l1 = new ListNode(1);
    		l1.next = new ListNode(2);
    		l1.next.next = new ListNode(3);
    		//设置参数2
    		ListNode l2 = new ListNode(1);
    		//调用参数
    		ListNode l3  = addTwoNumbers( l1,  l2);
    		//全部参数1
    		while (l1 != null) {
    			System.out.print(l1.val);
    			l1 = l1.next;
    			if (l1 != null) {
    				System.out.print("->");
    			}
    		}
    		System.out.println("//");
    		//全部参数2
    		while (l2 != null) {
    			System.out.print(l2.val);
    			l2 = l2.next;
    			if (l2 != null) {
    				System.out.print("->");
    			}
    		}
    		System.out.println("//");
    		//全部返回值
    		while (l3 != null) {
    			System.out.print(l3.val);
    			l3 = l3.next;
    			if (l3 != null) {
    				System.out.print("->");
    			}
    		}
    	}
    

      

  • 相关阅读:
    [noip2011d2t2]聪明的质检员 二分+前缀和优化
    [noip2016d2t2]蚯蚓
    KMP
    杨辉三角(二项式定理)&&组合数 【noip 2011/2016 d2t1】
    bzoj1615 [Usaco2008 Mar]The Loathesome Hay Baler麻烦的干草打包机
    [noip2015 pjt3]求和
    [周记]8.28~9.3
    [noip2011 d1t3] Mayan游戏
    react基础用法二(组件渲染)
    react基础用法一(在标签中渲染元素)
  • 原文地址:https://www.cnblogs.com/zhang20190701/p/13446407.html
Copyright © 2011-2022 走看看