题目1:【三数之和】力扣_15
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#!/bin/bash
#三数之和
#author:yzt 2019-10-24
#
echo "$1"|sed 's#\[\|\]##g'|sed 's#,#\n#g' > tmp1.txt #将输入数字转换为文档的每一行
declare -i aa=1
cat /dev/null >result.txt #初始化文档
cat /dev/null >tmp2.txt #初始化文档
for line in `cat tmp1.txt`
do
aa=$[$aa+1]
bb=1
sed -n "$aa,$ p" tmp1.txt >tmp2.txt #将$aa行之前的内容去掉并导入到文档tmp2.txt
test -s tmp2.txt||break #一个终止循环的监测点
for i in `cat tmp2.txt`
do
content=""
count1=$[$line + $i]
count2=$[-$count1]
bb=$[$bb+1]
sed -n "$bb,$ p" tmp2.txt >tmp3.txt
for j in `cat tmp3.txt`
do
if [ $j -eq $count2 ];then
echo "[$line,$i,$j]">>result.txt
fi
done
done
done
cat result.txt
脚本逻辑:
遍历所有的三元组合,并将某些和为0的三元组合输出到一个文档中
脚本效果:
[root@localhost leetcode]# ./sanshuzhihe.sh [-1,0,1,2,-1,-4]
[-1,0,1]
[-1,2,-1]
[0,1,-1]
[root@localhost leetcode]# ./sanshuzhihe.sh [-1,0,1,2,-1,-4,-7,-5,6,8]
[-1,0,1]
[-1,2,-1]
[-1,-7,8]
[-1,-5,6]
[0,1,-1]
[1,-7,6]
[-1,-7,8]
[-1,-5,6]
题目2:【最接近的三数之和】力扣_16
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
#!/bin/bash
#最接近的三数之和
#author:yzt 2019-10-25
#
read -t 20 -p "请输入给定的数组:" nums
read -t 20 -p "请输入一个目标值: " target
echo "$nums"|sed 's#\[\|\]##g'|sed 's#,#\n#g' > tmp1.txt
declare -i aa=1
cat /dev/null >result.txt
cat /dev/null >tmp2.txt
cat /dev/null >count.txt
for line in `cat tmp1.txt`
do
aa=$[$aa+1]
bb=1
sed -n "$aa,$ p" tmp1.txt >tmp2.txt
test -s tmp2.txt||break
for i in `cat tmp2.txt`
do
content=""
count1=$[$line + $i]
count2=$[-$count1]
bb=$[$bb+1]
sed -n "$bb,$ p" tmp2.txt >tmp3.txt
for j in `cat tmp3.txt`
do
echo "$line,$i,$j">>result.txt
done
done
done
awk -F , -v j=$target 'sum=$1+$2+$3-j {print sum}' result.txt >result1.txt
sed 's#^-##' result1.txt|grep -n -v "^$" >result2.txt
hangshu=`cat result2.txt|sort -t : -k2 -n|head -n1|awk -F : '{print $1}'`
sed -n "$hangshu p" result.txt
脚本逻辑:
先将所有三元组合输出到文档file1中,文档的三元组合求和并与目标值求差值,并结合行数输出到另一个文档file2中,格式如下:"1:5" "行数:三元和与目标值差值";根据差值进行排序,并选择第一个,即与目标值最接近的差值。由行数得出对应的三元组合。
脚本效果:
[root@localhost leetcode]# ./zuijiejindesanshuzhihe.sh
请输入给定的数组:[-1,2,1,-4]
请输入一个目标值: 1
-1,2,1
[root@localhost leetcode]# ./zuijiejindesanshuzhihe.sh
请输入给定的数组:[-8,6,4,8,9,21,-11]
请输入一个目标值: 6
-8,6,8