Two Sum Easy :给出一个数组,找出其中两个和为目标值

2018-10-20  本文已影响0人  woshi开心

第一种解题思路:目标值为d,循环遍历数组,访问数组中的每个元素,值设为a,查看d-a是否存在于数组中,如果存在则输出。

具体实现:

public static void main(String[] args) {

int[] a = {1, 2, 3, 4, 5, 6, 7};

    int dest =5;

    findIndex(a, 5);

}

public static void findIndex(int src[], int dest) {

for (int i =0; i < src.length; i++) {

int temp = dest - src[i];

        if (temp ==0) {System.out.println("i="+i);}

else {

for (int j = i +1; j < src.length; j++) {

      if (temp == src[j]) { System.out.println("i="+i +"  j=" + j);  }

}}}}

第二种解决思路:如果数组是一个排序数组,头尾两个指针,如果头尾两个相加小于目标值,则头指针向后移一位;如果头尾两个相加大于目标值,则尾指针向前移一位,直到头尾指针相等。

具体实现:

public static void main(String[] args) {

int a[]={1,2,3,4,5,6,7};

    findIndex(a,5);

}

public static void findIndex(int nums2[], int dest) {

HashMap hash=new HashMap();

    int first=0,second=nums2.length-1;

while(first<second){

if (nums2[first]==dest) {

hash.put(nums2[first],nums2[first]);

            System.out.println("first="+first+" first"+first);

            first++;

        }

if (nums2[second]==dest) {

hash.put(nums2[first],nums2[first]);

            System.out.println("first="+second+" first"+second);

            second--;

        }

if((nums2[first]+nums2[second])

first++;

        }else if((nums2[first]+nums2[second])>dest){

second--;

        }else {

System.out.println("first="+first+" second"+second);

            hash.put(nums2[first],nums2[second]);

            first++;

            second--;

        }

}

}

上一篇 下一篇

猜你喜欢

热点阅读