牛客刷题 数组求和

  在leetcode上刷到第一题,又在牛客上刷到与第一题相似的第二、第三题,整理如下:

第一题:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

解题思路:

public class Solution{
	public static void main(String args[]){

		int [] nums = {2, 7, 11, 15};
		int target=9;
		Solution s = new Solution();
		s.twoSum(nums, target);
	}
	public int[] twoSum(int[] nums, int target) {
		int i,j = 0;
        for(i=0;i

题目二:输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。对应每个测试案例,输出两个数,小的先输出。

解题思路:

public class Solution{
	public static void main(String args[]){
		int[] array={1,2,3,4,5,6,7};
		int sum =8;
		Solution s= new Solution();
		s.FindNumbersWithSum(array, sum);
	}
	public ArrayList FindNumbersWithSum(int [] array,int sum) {
		ArrayList  list=new  ArrayList();
		
		int min = 0;
		int max = array.length -1;
		int a1 = 0 ;
		int a2 =0;
		
		int chen=0;
		for(int i=0;minsum) max--;
			if(array[min]+array[max]

题目三:小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

解题思路:

public class Solution{
	public ArrayList> FindContinuousSequence(int sum){
		ArrayList> list = new ArrayList>();
		int min = 1;
		int max = 2;
		while(max arr = new ArrayList();
				for(int i=min;i<=max;i++){
					arr.add(i);
				}
				list.add(arr);
				min+=1;
				max+=1;
			}
			if((min+max)*(max-min+1)/2>sum){
				min+=1;
			}
		}
		return list;   
    }
}

 

你可能感兴趣的:(牛客刷题 数组求和)