【leetCode】1_两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2], tans = new int[2];
        int[] temp = new int[nums.length];
        temp = nums.clone();
        MySort(nums, 0, nums.length - 1);
        int l = 0;
        int r = nums.length - 1;
        while(l < r){
            if (nums[l] + nums[r] == target){
                tans[0] = l;
                tans[1] = r;
                break;
            }
            else if (nums[l] + nums[r] > target){
                r --;
                continue;
            }
            else{
                l ++;
                continue;
            }
        }
        for (int i = 0, j = 0; i < nums.length && j < 2; i ++){
            if (temp[i] == nums[tans[0]] || temp[i] == nums[tans[1]]){
                ans[j] = i;                
                j ++;
            }
        }
        return ans;
    }
    public void MySort(int[] nums, int l, int r){
        if (l >= r)
            return;
        int t = nums[l];
        int tl = l;
        int tr = r;
        while(r > l){
            while(r > l && nums[r] >= t){
                r --;
            }
            if (r > l){
                nums[l] = nums[r];
            }
            while(r > l && nums[l] <= t){
                l ++;
            }
            if (r > l){
                nums[r] = nums[l];
            }
        }
        nums[l] = t;
        MySort(nums, tl, l - 1);
        MySort(nums, r + 1, tr);
    }
}

 

你可能感兴趣的:(leetCode)