zoukankan      html  css  js  c++  java
  • [LeetCode#1] Two Sum

    The Problem:

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    Analysis: 

    The idea of the algorithm is classic, we need to use the search window and invariant to understand the idea behind it. 

    1. search window 

    front ......... end

    the search window is  num[front, end]. 

    2. the invariant <The right answers must be in the search window>

    we only to make sure that the right elements are always in the search window when we make decision about moving pointer, we could finally reach the right answer. 

    Note : assume the num array has already been sorted.

    iff num[front] + num[end] < target, we move front : front ++.

    All combination of num[i] and num[j], meeting the condition num[i] + num[j] > num[front] + num[end] is the search window. the answer must in it too!!!  

    iff num[front] + num[end] > target, we move end : end --. 

    The invariant: the right answer is always in the search window. (keep closing by moving pointer)

    proof:

    iff num[front] + num[end] < target,

    we move end to end': end --. num[front] + num[end'] < target, since num[end'] <= num[end].

    The right solution may not be contained in the search window. 

    Pitfall:

    Since the question ask us to return the index, so we need to research the answer's index at its original array. (it means we should copy the whole array to make the sorting.)

    My solution: 

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            
            int len = numbers.length;
            int[] sorted = new int[len];
            int[] obj = new int[2]; //used to contain value that meet obj[0] + obj[1] = target 
            int[] ret = new int[2]; //used to contain the index of obj[0] and obj[1] in original array
            int index_front;
            int index_end;
          
            System.arraycopy(numbers, 0, sorted, 0, len); // must use a copy to sort, at last, we need to finde the original index
            Arrays.sort(sorted);
            
            int front = 0;
            int end = len - 1;
            
            while (front < end) {  //take care of the index conversion!
                if (sorted[front] + sorted[end] == target) {
                    break;
                } else if (sorted[front] + sorted[end] < target ) {
                    front ++;
                } else {
                    end --; 
                }
            }
            
            obj[0] = sorted[front];
            obj[1] = sorted[end];
            ret = find_indexes(numbers, obj);
            
            ret[0] ++;
            ret[1] ++;
            Arrays.sort(ret);
            return ret;
        }
        
        static int[] find_indexes(int[] numbers, int[] obj) { 
            int[] ret = new int[2];
            ret[0] = -1; //must set to -1, cause the following check condition 
            ret[1] = -1; 
            for (int i = 0; i < numbers.length; i++) { //must check ret[0] == -1, otherwise, ret[1] would never be assigned
                    if (numbers[i] == obj[0] && ret[1] != i && ret[0] == -1) { // avoid to count the same element twice
                        ret[0] = i;
                    }
                    if (numbers[i] == obj[1] && ret[0] != i && ret[1] == -1) { 
                        ret[1] = i; 
                    }
            }
            return ret;
        }
    }

    note: when we search for two distinct elements in the same array, we must make sure they were assigned with different indexes(elements).

    A tricky skill to achieve is to check if the element has already been assigned, by checking the ans[m] == i . 

            ret[0] = -1; //must set to -1, cause the following check condition 
            ret[1] = -1; 
            for (int i = 0; i < numbers.length; i++) { //must check ret[0] == -1, otherwise, ret[1] would never be assigned
                    if (numbers[i] == obj[0] && ret[1] != i && ret[0] == -1) { // avoid to count the same element twice
                        ret[0] = i;
                    }
                    if (numbers[i] == obj[1] && ret[0] != i && ret[1] == -1) { 
                        ret[1] = i; 
                    }
            }
    numbers[i] == obj[0]: guarantee the element is the right element we searching for.
    ret[1] != i : guarantee the element was not assigned to others. 
    ret[0] == -1 : guarantee the elements' with the same vlue are not assgined to a single variable twice. 
    take care: (The elements with the same value!)(-1 is great when search in array)
  • 相关阅读:
    jQuery:balloon气泡提示插件
    等高布局
    html5 语音搜索
    JS编码三种方法的区别:escape、encodeURI和encodeURIComponent
    为什么要两次调用encodeURI来解决乱码问题
    关于时间差查询的一个小技巧
    MySQL对时间的处理总结
    闭包总结:从执行环境来看闭包和垃圾回收
    闭包总结:闭包的7种形式
    JavaScript里面向对象的继承:不使用构造函数实现"继承"
  • 原文地址:https://www.cnblogs.com/airwindow/p/4192759.html
Copyright © 2011-2022 走看看