zoukankan      html  css  js  c++  java
  • 找一对数

    输入n个整数,找出其中两个数,他们之和等于整数m 如果存在输出 true 不存在输出false
    我这里用的是二分查找以及双指针

    双指针

    二分查找

    public class Main {
     
    	public static boolean sumSearch(int arr[], int a) {
    		int i = 0;
    		int j = arr.length - 1;
    		Arrays.sort(arr);
    		while (i < j) {
    			if (arr[j] + arr[i] < a) {
    				i++;
    			} else if (arr[j] + arr[i] > a) {
    				j--;
    			} else if (arr[j] + arr[i] == a)
    				return true;
    		}
    		return false;
    	}
     
    	public static boolean sumBinarySearch(int arr[], int a) {
    		Arrays.sort(arr);
    		for (int x = 0; x < arr.length; x++) {
    			int y = x + 1;
    			int z = arr.length - 1;
    			int temp = a - arr[x];
    			while (y <= z) {
    				if (temp < arr[(y + z) / 2])
    					z = (y + z) / 2 - 1;
    				else if (temp > arr[(y + z) / 2])
    					y = (y + z) / 2 + 1;
    				else if (temp == arr[(y + z) / 2])
    					return true;
    			}
    		}
    		return false;
    	}
     
    	public static void main(String[] args) {
    		int A[] = { 5, 2, 6, 2, 3, 2 };
    		System.out.println(sumSearch(A, 10));
    		System.out.println(sumBinarySearch(A, 10));
    	}
    }
    
  • 相关阅读:
    LeetCode: 18. 4Sum
    LeetCode:15. 3Sum
    Leetcode:1. Two Sum
    tensorflow placeholder
    Tensorflow变量
    13.git的简单使用
    13.Django1.11.6文档
    12.python进程协程异步IO
    12.Flask-Restful
    12.Django思维导图
  • 原文地址:https://www.cnblogs.com/cznczai/p/11149923.html
Copyright © 2011-2022 走看看