Leetcode學習

ahuljy發表於2019-10-21

package com.pajk.recsyssort.lc;

public class lc1 {

public int[] twosum(int[] nums, int target){

    int i = 0;
    int j = 0;
    int[] result = new int[2];

    for( i = 0;i<nums.length; i++){
        for(j = i+1;j<nums.length;j++){
            if(nums[j]== target- nums[i]){
                result[0] = i;
                result[1] = j;
                return result;
            }
        }
    }
    return result;
}

public static void main(String[] args){
    int[] nums = {1,4,5,9};
    int target = 10;
    lc1 twoSum = new lc1();
    //int[] result = new int[];
    int[] result  = twoSum.twosum(nums, target);
    for(int a: result)
        System.out.println(a);
}

}

package com.pajk.recsyssort.lc;

public class lc2 {

public class ListNode{
    public int val;
    public ListNode next;
    public ListNode(int x){val = x;}
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2){
    int nums = 0;
    ListNode ProNode = new ListNode(0);
    ListNode currentNode = new ListNode(0);
    ProNode.next = currentNode;

    do{
        int sum = (l1!=null?l1.val: 0) + (l2!=null?l2.val:0) + nums;
        nums = sum/10;
        int result = sum%10;
        currentNode.val = result;
        l1 = l1!=null?l1.next: l1;
        l2 = l2!=null?l2.next: l2;
        if(l1!=null || l2!=null || nums!=0){
            currentNode.next = new ListNode(0);
            currentNode = currentNode.next;
        }
    }while(l1!=null || l2!=null ||nums!=0);
    return ProNode.next;
}

public void outPutResult(ListNode ls){
    while (ls!=null){
        System.out.print(ls.val + " ");
        ls = ls.next;
    }
    System.out.println("\n");
}

/**
 * 將陣列轉換為ListNode
 * @param arr
 * @return
 */

public ListNode arrToList(int[] arr){
    ListNode result = null;
    ListNode p = null;
    for(int i = 0; i<arr.length; i++){
        if(result == null){
            p = new ListNode(arr[i]);
            result = p;
        }
        else{
            p.next = new ListNode(arr[i]);
            p = p.next;
        }
    }
    return result;
}

public static void main(String []args){
    int[] arr1 = {2,0,5};
    int[] arr2 = {3,7,6};
    lc2 ad = new lc2();
    ListNode l1 = ad.arrToList(arr1);
    ListNode l2 = ad.arrToList(arr2);
    ad.outPutResult(l1);
    ad.outPutResult(l2); //將陣列轉換成連結結構儲存,以後後續操作

    ListNode result = ad.addTwoNumbers(l1,l2); //呼叫方法addTwoNumbers對兩個連結相加
    ad.outPutResult(result);

}

}

public class lc9 { public boolean isPalindrome(int x){ String s = Integer.toString(x); boolean flag = true; int s_len = s.length(); for (int i = 0; i

public static void main(String []args){
    lc9 isp = new lc9();
    int x = 12343210;
    boolean result = isp.isPalindrome(x);
    System.out.println(result);

}

}

相關文章