[Algorithm learning] Given an integer array, find two integers for the specified integer and (1)

Source: Internet
Author: User

Question description: Given an integer array, is it possible to find out two of them and make them a specified value? (assumed to be unordered arrays)

Solution One: Brute force (exhaustive method, not advocated)
  
 
  1. /**
  2. * 暴力破解
  3. * (穷举,时间复杂度:O(n^2),正常是不会用这个滴,假如只是为了快速解题,对时间没有限制,用这个最简单)
  4. *
  5. * @param nums
  6. * @param target
  7. */
  8. public static void findTwo1(int[] nums, int target)
  9. {
  10. int one, two;
  11. for (int i = 0; i < nums.length; i++)
  12. {
  13. one = nums[i];
  14. two = target - one;
  15. for (int j = 0; j < nums.length; j++)
  16. {
  17. if (i != j)
  18. {
  19. if (two == nums[j])
  20. {
  21. System.out.println("one:" + one + " two:" + two);
  22. return;
  23. }
  24. }
  25. }
  26. }
  27. System.out.println("找不到这两个数");
  28. }
Solution 2:2 Method (equivalent to two pointers)
  
 
  1. /**
  2. * 两个指针二分查找
  3. * (排序时间复杂度为O(nlog(n)),while最多O(N),所以最终程序的时间复杂度为:O(nlo(n)))
  4. *
  5. * @param nums
  6. * @param target
  7. */
  8. public static void findTwo2(int[] nums, int target)
  9. {
  10. // 1.排列(用的是Dual-Pivot Quicksort(快速排序),时间复杂度为O(nlog(n)))
  11. Arrays.sort(nums);
  12. // 2.类二分查找
  13. int left = 0;
  14. int right = nums.length - 1;
  15. while (left < right)
  16. {
  17. if (nums[left] + nums[right] > target)
  18. {// 太大 right减少
  19. right--;
  20. }
  21. else if (nums[left] + nums[right] < target)
  22. {// 太小left增加
  23. left++;
  24. }
  25. else
  26. {// 找到结果,结束查找
  27. System.out.println("one:" + nums[left] + " two:" + nums[right]);
  28. return;
  29. }
  30. }
  31. System.out.println("找不到这两个数");
  32. }


From for notes (Wiz)

[Algorithm learning] Given an integer array, find two integers for the specified integer and (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.