1. 程式人生 > 實用技巧 >Git基礎與Github

Git基礎與Github

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("->");
			}
		}
	}