nums = [1,2,3,4,5,6] #假如这是给定的数组
target = 9 #假如这是给定的目标值
num_list = [] #用来装结果的容器
def run(nums,target):
'''功能函数'''
for num1 in nums:
for num2 in nums:
if num1 + num2 == target:
num_list.append(num1)
num_list.append(num2)
print(num_list)
break
if num_list:
break
if __name__ == '__main__':
run(nums,target)
import java.util.ArrayList;
public class Demo01 {
public static void main(String[] args) {
//用来存放检测的数据
ArrayList<Integer> nums = new ArrayList<>();
//假设此时的数据
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(6);
nums.add(7);
nums.add(5);
//假设此时的target数据为9
int target = 9;
//调用函数
getResult(nums, target);
}
public static void getResult(ArrayList<Integer> nums, int target) {
//用来存放及结果数据
ArrayList<Integer> result = new ArrayList<>();
//设置标志
boolean status = false;
for (int i = 0; i < nums.size(); i++) {
for (int i1 = 0; i1 < nums.size(); i1++) {
if (nums.get(i) + nums.get(i1) == target) {
result.add(nums.get(i));
result.add(nums.get(i1));
status = true;
System.out.println(result);
break;
}
}
if (status) {
break;
}
}
}
}