88. Merge Sorted Array 167. Two Sum II

来源:互联网 发布:深入php内核 编辑:程序博客网 时间:2024/05/22 02:54

88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

这道题是给定两个排好序的数组,将它们合并后放到nums1中,使nums1是有序的。并且假定nums1的空间足够容纳两个数组的所有元素。我用了一个for循环,先将nums2中的元素全部放到nums1后面,然后对nums1排序。但是这种方法效率太低,只打败了6.8%的提交结果。

for(int i=0;i<n;i++){    nums1[i+m]=nums2[i];    }Arrays.sort(nums1);

另一种解法,只用了一行程序,打败了48%左右的提交结果,用了while循环,通过比较nums1与nums2中元素的大小得到合并并排序的nums1:

while(n>0) nums1[m+n-1] = (m==0||nums2[n-1] > nums1[m-1]) ? nums2[--n] : nums1[--m];
167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.

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

这道题跟之前的Two Sum很像,只是加了要求,返回的索引按升序排列,用了一个HashMap,来保存数组元素和索引之间的映射,代码如下:

       HashMap<Integer,Integer> map = new HashMap<>();        int len = numbers.length;       int [] res = new int [2];       for(int i=0;i<len;i++){       if(map.containsKey(target-numbers[i])){       res[0]=map.get(target-numbers[i])+1;       res[1]=i+1;       }       else map.put(numbers[i],i);       }       //Arrays.sort(res);       return res;

另一种解法,效率更高,这里充分利用了数组是排好序的,如果二者之和大于target,就让大的索引r减小,否则增大小的索引l:

        int l = 0, r = numbers.length - 1;        while (numbers[l] + numbers[r] != target) {            if (numbers[l] + numbers[r] > target) r--;            else l++;        }        return new int[]{l + 1, r + 1};


0 0
原创粉丝点击