Two Sum - novice on the road

Posted by takeiteasy on Mon, 02 Dec 2019 18:21:27 +0100

 

Not graduated from computer related major, never used leetcode. Recently, I am learning data structure and algorithm, and practicing with leetcode.

If there is something wrong with the code, just point it out.

Today's first question: Two Sum

The topics are as follows:

Solution:

In the existing array nums[p-r], first order nums from small to large, and then compare nums[p] + nums[r] with the specified value K. if nums[p] + nums[r] > k, it means nums[r] is large, r --;

On the contrary, p + +, until nums[p] + nums[r] = k.

Here is my Java implementation (to be honest, time complexity is high)

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int[] copyNums = new int[nums.length];
 4         for(int i = 0; i < nums.length; ++i){
 5             copyNums[i] = nums[i];
 6         }
 7         int[] result = new int[2];
 8         
 9         // Prioritize
10         quickSort(nums, 0, nums.length - 1);
11         
12         // Combine the two elements with target Comparison
13         int[] temp = compare(nums, 0, nums.length - 1, target);
14         
15         boolean flagA = false;
16         boolean flagB = false;
17         for(int i = 0; i < copyNums.length; ++i){
18             if(temp[0] == copyNums[i] && !flagA){
19                 result[0] = i;
20                 flagA = true;
21                 continue;
22             }
23             if(temp[1] == copyNums[i] && !flagB){
24                 result[1] = i;
25                 flagB = true;
26             }
27         }
28         return result;
29     }
30     
31     private int[] compare(int[] nums, int p, int r, int target){
32         while(p < r){
33             int k = nums[p] + nums[r];
34             if(k == target)
35                 return new int[]{nums[p], nums[r]};
36             if(k > target){
37                 r--;
38             }else{
39                 p++;
40             }
41         }
42         return null;
43     }
44     
45     private void quickSort(int[] nums, int p, int r){
46         if(p >= r)
47             return;
48         int q = partition(nums, p, r);
49         quickSort(nums, p, q-1);
50         quickSort(nums, q+1, r);
51     }
52     
53     private int partition(int[] nums, int p, int r){
54         // The simplest, choice nums Last element as middle number
55         int k = nums[r];
56         int i = p;
57         
58         for(int j = p; j <= r; j++){
59             if(nums[j] < k){
60                 int temp = nums[i];
61                 nums[i] = nums[j];
62                 nums[j] = temp;
63                 ++i;
64             }
65         }
66         
67         nums[r] = nums[i];
68         nums[i] = k;
69         
70         return i;
71     }
72 }

Topics: Java